mirror of
https://github.com/paperless-ngx/paperless-ngx.git
synced 2026-11-29 08:13:19 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aad70575b7 |
No files matched your search
@@ -8,7 +8,7 @@ ARG DEBIAN_FRONTEND=noninteractive
|
|||||||
ARG TARGETARCH
|
ARG TARGETARCH
|
||||||
|
|
||||||
# Can be workflow provided, defaults set for manual building
|
# Can be workflow provided, defaults set for manual building
|
||||||
ARG JBIG2ENC_VERSION=0.32
|
ARG JBIG2ENC_VERSION=0.30
|
||||||
|
|
||||||
# Set Python environment variables
|
# Set Python environment variables
|
||||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||||
|
|||||||
@@ -87,6 +87,7 @@ src/documents/classifier.py:0: error: Incompatible types in assignment (expressi
|
|||||||
src/documents/classifier.py:0: error: Incompatible types in assignment (expression has type "None", variable has type "DocumentClassifier") [assignment]
|
src/documents/classifier.py:0: error: Incompatible types in assignment (expression has type "None", variable has type "DocumentClassifier") [assignment]
|
||||||
src/documents/classifier.py:0: error: Incompatible types in assignment (expression has type "None", variable has type "DocumentClassifier") [assignment]
|
src/documents/classifier.py:0: error: Incompatible types in assignment (expression has type "None", variable has type "DocumentClassifier") [assignment]
|
||||||
src/documents/classifier.py:0: error: Incompatible types in assignment (expression has type "str", variable has type "None") [assignment]
|
src/documents/classifier.py:0: error: Incompatible types in assignment (expression has type "str", variable has type "None") [assignment]
|
||||||
|
src/documents/classifier.py:0: error: Item "None" of "str | None" has no attribute "encode" [union-attr]
|
||||||
src/documents/classifier.py:0: error: List comprehension has incompatible type List[int]; expected List[list[int]] [misc]
|
src/documents/classifier.py:0: error: List comprehension has incompatible type List[int]; expected List[list[int]] [misc]
|
||||||
src/documents/classifier.py:0: error: Module "sklearn.exceptions" has no attribute "InconsistentVersionWarning" [attr-defined]
|
src/documents/classifier.py:0: error: Module "sklearn.exceptions" has no attribute "InconsistentVersionWarning" [attr-defined]
|
||||||
src/documents/classifier.py:0: error: Unsupported operand types for >= ("datetime" and "None") [operator]
|
src/documents/classifier.py:0: error: Unsupported operand types for >= ("datetime" and "None") [operator]
|
||||||
|
|||||||
@@ -50,7 +50,7 @@ repos:
|
|||||||
- 'prettier-plugin-organize-imports@4.3.0'
|
- 'prettier-plugin-organize-imports@4.3.0'
|
||||||
# Python hooks
|
# Python hooks
|
||||||
- repo: https://github.com/astral-sh/ruff-pre-commit
|
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||||
rev: v0.17.6
|
rev: v0.17.2
|
||||||
hooks:
|
hooks:
|
||||||
- id: ruff-check
|
- id: ruff-check
|
||||||
- id: ruff-format
|
- id: ruff-format
|
||||||
|
|||||||
@@ -896,6 +896,13 @@
|
|||||||
"concise_description": "Unexpected keyword argument `fast` in function `tantivy.tantivy.SchemaBuilder.add_json_field`",
|
"concise_description": "Unexpected keyword argument `fast` in function `tantivy.tantivy.SchemaBuilder.add_json_field`",
|
||||||
"severity": "error"
|
"severity": "error"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"column": 9,
|
||||||
|
"path": "src/documents/serialisers.py",
|
||||||
|
"name": "bad-override-param-name",
|
||||||
|
"concise_description": "Class member `MatchingModelSerializer.validate` overrides parent class `ModelSerializer` in an inconsistent manner",
|
||||||
|
"severity": "error"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"column": 62,
|
"column": 62,
|
||||||
"path": "src/documents/serialisers.py",
|
"path": "src/documents/serialisers.py",
|
||||||
@@ -945,6 +952,13 @@
|
|||||||
"concise_description": "Cannot set item in `Mapping[str, Any]`",
|
"concise_description": "Cannot set item in `Mapping[str, Any]`",
|
||||||
"severity": "error"
|
"severity": "error"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"column": 9,
|
||||||
|
"path": "src/documents/serialisers.py",
|
||||||
|
"name": "bad-override-param-name",
|
||||||
|
"concise_description": "Class member `TagSerializer.validate` overrides parent class `MatchingModelSerializer` in an inconsistent manner",
|
||||||
|
"severity": "error"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"column": 17,
|
"column": 17,
|
||||||
"path": "src/documents/serialisers.py",
|
"path": "src/documents/serialisers.py",
|
||||||
|
|||||||
+1
-1
@@ -99,7 +99,7 @@ ARG DEBIAN_FRONTEND=noninteractive
|
|||||||
ARG TARGETARCH
|
ARG TARGETARCH
|
||||||
|
|
||||||
# Can be workflow provided, defaults set for manual building
|
# Can be workflow provided, defaults set for manual building
|
||||||
ARG JBIG2ENC_VERSION=0.32
|
ARG JBIG2ENC_VERSION=0.30
|
||||||
|
|
||||||
# Set Python environment variables
|
# Set Python environment variables
|
||||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||||
|
|||||||
@@ -285,12 +285,6 @@ The API supports various bulk-editing operations which are executed asynchronous
|
|||||||
|
|
||||||
### Documents
|
### 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
|
For bulk operations on documents, use the endpoint `/api/documents/bulk_edit/` which accepts
|
||||||
a json payload of the format:
|
a json payload of the format:
|
||||||
|
|
||||||
|
|||||||
@@ -1,121 +1,5 @@
|
|||||||
# Changelog
|
# 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
|
## paperless-ngx 3.4.2
|
||||||
|
|
||||||
### Bug Fixes
|
### Bug Fixes
|
||||||
|
|||||||
+3
-23
@@ -510,9 +510,9 @@ You can read more about this in [the Django project's documentation](https://doc
|
|||||||
|
|
||||||
- With neither setting configured, Paperless accepts any host.
|
- With neither setting configured, Paperless accepts any host.
|
||||||
- With only `PAPERLESS_URL` set, Paperless accepts the hostname from that URL
|
- With only `PAPERLESS_URL` set, Paperless accepts the hostname from that URL
|
||||||
and the loopback hosts `localhost`, `127.0.0.1`, and `[::1]`.
|
and `localhost` (used by the Docker health check).
|
||||||
- `PAPERLESS_ALLOWED_HOSTS` adds hosts to those loopback hosts and the hostname
|
- `PAPERLESS_ALLOWED_HOSTS` adds hosts to `localhost` and the hostname from
|
||||||
from `PAPERLESS_URL`, if set. A blank list adds no hosts.
|
`PAPERLESS_URL`, if set. A blank list adds no hosts.
|
||||||
- With `PAPERLESS_ALLOWED_HOSTS=*`, Paperless accepts any host, even when
|
- With `PAPERLESS_ALLOWED_HOSTS=*`, Paperless accepts any host, even when
|
||||||
`PAPERLESS_URL` is set.
|
`PAPERLESS_URL` is set.
|
||||||
|
|
||||||
@@ -551,12 +551,6 @@ when its IPv4 and IPv6 addresses are both listed in
|
|||||||
Only trust `X-Forwarded-For` when untrusted clients cannot connect directly
|
Only trust `X-Forwarded-For` when untrusted clients cannot connect directly
|
||||||
to Paperless-ngx.
|
to Paperless-ngx.
|
||||||
|
|
||||||
This count also controls which address Django REST Framework uses from
|
|
||||||
`X-Forwarded-For` for the API token throttle. With a count of zero, the
|
|
||||||
throttle uses the connecting address instead. If
|
|
||||||
`PAPERLESS_ALLAUTH_TRUSTED_CLIENT_IP_HEADER` is set, the token throttle
|
|
||||||
uses the connecting address regardless of this count.
|
|
||||||
|
|
||||||
Defaults to the number of entries in `PAPERLESS_TRUSTED_PROXIES`.
|
Defaults to the number of entries in `PAPERLESS_TRUSTED_PROXIES`.
|
||||||
|
|
||||||
#### [`PAPERLESS_ALLAUTH_TRUSTED_CLIENT_IP_HEADER=<header-name>`](#PAPERLESS_ALLAUTH_TRUSTED_CLIENT_IP_HEADER) {#PAPERLESS_ALLAUTH_TRUSTED_CLIENT_IP_HEADER}
|
#### [`PAPERLESS_ALLAUTH_TRUSTED_CLIENT_IP_HEADER=<header-name>`](#PAPERLESS_ALLAUTH_TRUSTED_CLIENT_IP_HEADER) {#PAPERLESS_ALLAUTH_TRUSTED_CLIENT_IP_HEADER}
|
||||||
@@ -641,20 +635,6 @@ you're running two instances of paperless on the same host.
|
|||||||
|
|
||||||
Defaults to `""`, which does not alter the cookie names.
|
Defaults to `""`, which does not alter the cookie names.
|
||||||
|
|
||||||
#### [`PAPERLESS_COOKIE_SECURE=<bool>`](#PAPERLESS_COOKIE_SECURE) {#PAPERLESS_COOKIE_SECURE}
|
|
||||||
|
|
||||||
: Marks the session, CSRF and language cookies with the `Secure` attribute, so browsers only send them over HTTPS. This sets the Django settings [`SESSION_COOKIE_SECURE`](https://docs.djangoproject.com/en/stable/ref/settings/#session-cookie-secure), [`CSRF_COOKIE_SECURE`](https://docs.djangoproject.com/en/stable/ref/settings/#csrf-cookie-secure) and [`LANGUAGE_COOKIE_SECURE`](https://docs.djangoproject.com/en/stable/ref/settings/#language-cookie-secure) together.
|
|
||||||
|
|
||||||
Enable this if you access paperless exclusively over HTTPS, for example behind a reverse proxy which terminates TLS.
|
|
||||||
|
|
||||||
!!! warning
|
|
||||||
|
|
||||||
Browsers will not send `Secure` cookies over plain HTTP, so logging in over HTTP, for example directly via a LAN address which bypasses the reverse proxy, will fail. Some browsers make an exception for `localhost`.
|
|
||||||
|
|
||||||
After changing this, you may have to login again.
|
|
||||||
|
|
||||||
Defaults to `false`.
|
|
||||||
|
|
||||||
#### [`PAPERLESS_ENABLE_HTTP_REMOTE_USER=<bool>`](#PAPERLESS_ENABLE_HTTP_REMOTE_USER) {#PAPERLESS_ENABLE_HTTP_REMOTE_USER}
|
#### [`PAPERLESS_ENABLE_HTTP_REMOTE_USER=<bool>`](#PAPERLESS_ENABLE_HTTP_REMOTE_USER) {#PAPERLESS_ENABLE_HTTP_REMOTE_USER}
|
||||||
|
|
||||||
: Allows authentication via HTTP_REMOTE_USER which is used by some SSO
|
: Allows authentication via HTTP_REMOTE_USER which is used by some SSO
|
||||||
|
|||||||
+5
-99
@@ -109,7 +109,7 @@ Think of versions as **file history** for a document.
|
|||||||
Paperless-ngx includes management lists for tags, correspondents, document types
|
Paperless-ngx includes management lists for tags, correspondents, document types
|
||||||
and more. These areas allow you to view, add, edit, delete and manage permissions
|
and more. These areas allow you to view, add, edit, delete and manage permissions
|
||||||
for these objects. You can also manage saved views, mail accounts, mail rules,
|
for these objects. You can also manage saved views, mail accounts, mail rules,
|
||||||
workflows, [OCR templates](#ocr-templates) and more from the management sections.
|
workflows and more from the management sections.
|
||||||
|
|
||||||
### Nested Tags
|
### Nested Tags
|
||||||
|
|
||||||
@@ -587,10 +587,9 @@ documents from the web UI:
|
|||||||
- From the document list, select one or more documents and choose **Run workflow** from the "Actions" menu.
|
- From the document list, select one or more documents and choose **Run workflow** from the "Actions" menu.
|
||||||
- From an individual document, choose **Run workflow** from the "Actions" menu.
|
- From an individual document, choose **Run workflow** from the "Actions" menu.
|
||||||
|
|
||||||
You will be asked which workflow to run. From the document list, the workflow's trigger filters apply by default, so
|
You will be asked which workflow to run. By default the workflow's trigger filters still apply, so documents that do
|
||||||
documents that do not match are skipped. You can choose to **run on all selected documents** to ignore the filters.
|
not match are skipped. You can instead choose to **run on all selected documents**, which ignores the trigger filters
|
||||||
From an individual document, the option to ignore trigger filters is selected by default. Clear it to run the workflow
|
and runs the workflow's actions on every selected document.
|
||||||
only if the document matches its trigger filters.
|
|
||||||
|
|
||||||
Manual runs happen in the background. As with scheduled workflows, the document list is not refreshed automatically when
|
Manual runs happen in the background. As with scheduled workflows, the document list is not refreshed automatically when
|
||||||
they finish, so you may need to reload the list to see the results.
|
they finish, so you may need to reload the list to see the results.
|
||||||
@@ -659,7 +658,7 @@ will be aborted and the file will be deleted.
|
|||||||
|
|
||||||
"Password Removal" actions attempt to remove password protection from encrypted PDF documents. You can specify:
|
"Password Removal" actions attempt to remove password protection from encrypted PDF documents. You can specify:
|
||||||
|
|
||||||
- One or more passwords to try, one per line (commas within a password are supported)
|
- One or more passwords to try, separated by commas or new lines
|
||||||
- Each password is tried in order until one successfully unlocks the document
|
- Each password is tried in order until one successfully unlocks the document
|
||||||
|
|
||||||
Password removal never modifies a file in place. Instead, once a working password is found, the
|
Password removal never modifies a file in place. Instead, once a working password is found, the
|
||||||
@@ -821,99 +820,6 @@ The following custom field types are supported:
|
|||||||
- `Document Link`: reference(s) to other document(s) displayed as links, automatically creates a symmetrical link in reverse
|
- `Document Link`: reference(s) to other document(s) displayed as links, automatically creates a symmetrical link in reverse
|
||||||
- `Select`: a pre-defined list of strings from which the user can choose
|
- `Select`: a pre-defined list of strings from which the user can choose
|
||||||
|
|
||||||
## OCR Templates {#ocr-templates}
|
|
||||||
|
|
||||||
OCR templates read text from fixed areas ("zones") of a document and write it to a
|
|
||||||
[custom field](#custom-fields), or to the document's title, archive serial number or created date. They are
|
|
||||||
useful for documents that always share the same layout, such as bills from a particular utility. They allow you
|
|
||||||
to draw a zone around the account number once, and every new bill gets its account number filled in.
|
|
||||||
|
|
||||||
Like tags or document types, each template has a [matching algorithm](advanced_usage.md#matching) that
|
|
||||||
decides which documents it automatically applies to (or not), based on their content.
|
|
||||||
|
|
||||||
### Creating a template
|
|
||||||
|
|
||||||
1. Open **OCR Templates** under "Manage" and choose **Add Template**.
|
|
||||||
2. Give the template a name and set up its matching, for example **Any word** with the utility's name. Choose
|
|
||||||
**None** for a template that should only ever be run manually.
|
|
||||||
3. Search for a sample document with the layout the template is for. Its pages are shown next to the template
|
|
||||||
settings.
|
|
||||||
4. Draw zones on the document. Click a zone to select and edit it.
|
|
||||||
5. Choose the field each zone fills.
|
|
||||||
6. Use **Test** to run OCR on the selected zone of the sample document and see the text it finds and the value
|
|
||||||
that would be written.
|
|
||||||
|
|
||||||
Zones are positioned relative to the sample document's page, so templates work best when the documents they
|
|
||||||
match have an identical layout. Keep the matching specific enough that it only catches documents with that
|
|
||||||
layout. When more than one template applies to a document, the first one by name fills a field and later
|
|
||||||
templates do not overwrite it.
|
|
||||||
|
|
||||||
### Zone settings
|
|
||||||
|
|
||||||
- **Page**: the page the zone is on. Turn on **Last page** for zones that are always on the final page,
|
|
||||||
regardless of how many pages a document has. If the number of pages cannot be determined, the zone is skipped.
|
|
||||||
- **OCR language**: the Tesseract languages used to read the zone. Languages other than the defaults must be
|
|
||||||
installed, see [`PAPERLESS_OCR_LANGUAGES`](configuration.md#PAPERLESS_OCR_LANGUAGES).
|
|
||||||
- **Transform**: post-processing applied to the text, such as stripping whitespace, keeping only numbers,
|
|
||||||
parsing a date or reading a QR code or barcode instead of text.
|
|
||||||
- **Date format**: for the "Parse date" transform, the format of the date using
|
|
||||||
[Python date codes](https://docs.python.org/3/library/datetime.html#format-codes), e.g. `%d.%m.%Y`.
|
|
||||||
Leave it empty to detect the format automatically.
|
|
||||||
- **Validation regex**: a regular expression the whole value must match. Values that do not match are not
|
|
||||||
written.
|
|
||||||
|
|
||||||
Zones can fill custom fields of type text, long text, URL, date, integer, number, monetary or boolean.
|
|
||||||
Document link and select fields are not supported.
|
|
||||||
|
|
||||||
### Combining zones
|
|
||||||
|
|
||||||
When several zones fill the same field, a **Combined value** setting appears for that field. Use it to arrange
|
|
||||||
the zones' values with `{Zone name}` tokens and any text in between, for example `{Start} - {End}`. If it
|
|
||||||
is left empty, the values are joined with spaces in zone order.
|
|
||||||
|
|
||||||
### When templates run
|
|
||||||
|
|
||||||
When a document is added, every enabled template that matches its content runs automatically, reading the
|
|
||||||
zones from the archived file, or from the original PDF or image when there is no archived file. A template is
|
|
||||||
only used if the document's owner can view it, so users' templates apply to their own documents, and unowned
|
|
||||||
templates apply to everyone's. The owner here is the one set by the upload, the mail rule or a consumption
|
|
||||||
workflow. A document without an owner at that point, for example from the consume folder or a mail rule
|
|
||||||
without an owner, considers every enabled template. An owner assigned later by a "Document Added" workflow
|
|
||||||
does not change which templates ran. Templates run in name order, so if two templates fill the same field, the
|
|
||||||
later one wins.
|
|
||||||
|
|
||||||
Zone OCR keeps values supplied when the document is consumed: an uploaded title, ASN, created date or custom
|
|
||||||
field value, a mail rule's title, a barcode ASN, and values assigned by a consumption workflow. Zones fill the
|
|
||||||
remaining fields before "Document Added" workflows run, so those workflows can use or overwrite the values.
|
|
||||||
|
|
||||||
Turn off **Enabled** to pause a template without deleting it. Disabled templates never run automatically, but
|
|
||||||
can still be run manually.
|
|
||||||
|
|
||||||
### Running templates manually
|
|
||||||
|
|
||||||
To run templates on documents that are already in Paperless-ngx, open the **Actions** menu on the document
|
|
||||||
details page:
|
|
||||||
|
|
||||||
- **Run Zone OCR** runs every enabled template that matches the document.
|
|
||||||
- The button next to it opens a dialog where you can choose one template to run
|
|
||||||
instead. A template you choose runs even if it does not match the document or is disabled.
|
|
||||||
|
|
||||||
Both actions use the file version selected in document details. The latest version is selected by default.
|
|
||||||
Extracted values update the document's metadata, which is shared across its versions. If no template
|
|
||||||
applies to the document, nothing is run. Otherwise the run is processed in the background and appears in the
|
|
||||||
task list. The document shows the extracted values once the task finishes.
|
|
||||||
|
|
||||||
The bulk editor's **Run Zone OCR** action opens the same dialog for the selected documents. Bulk runs use
|
|
||||||
the latest version of each document and are processed in the background.
|
|
||||||
|
|
||||||
!!! warning
|
|
||||||
|
|
||||||
Running zone OCR manually or in bulk overwrites the fields it fills. A zone that finds no value leaves its
|
|
||||||
field unchanged.
|
|
||||||
|
|
||||||
Managing OCR templates requires the OCR template permissions. Running zone OCR on documents requires
|
|
||||||
permission to change them, and choosing a template requires permission to view it.
|
|
||||||
|
|
||||||
## PDF Actions
|
## PDF Actions
|
||||||
|
|
||||||
Paperless-ngx supports basic editing operations for PDFs (these operations currently cannot be performed on non-PDF files). When viewing an individual document you can
|
Paperless-ngx supports basic editing operations for PDFs (these operations currently cannot be performed on non-PDF files). When viewing an individual document you can
|
||||||
|
|||||||
+11
-23
@@ -1,6 +1,6 @@
|
|||||||
[project]
|
[project]
|
||||||
name = "paperless-ngx"
|
name = "paperless-ngx"
|
||||||
version = "3.5.1"
|
version = "3.4.2"
|
||||||
description = """\
|
description = """\
|
||||||
A community-supported supercharged document management system: scan, index and archive all your physical documents\
|
A community-supported supercharged document management system: scan, index and archive all your physical documents\
|
||||||
"""
|
"""
|
||||||
@@ -23,7 +23,6 @@ dependencies = [
|
|||||||
"channels~=4.2",
|
"channels~=4.2",
|
||||||
"channels-redis~=4.2",
|
"channels-redis~=4.2",
|
||||||
"concurrent-log-handler~=0.9.25",
|
"concurrent-log-handler~=0.9.25",
|
||||||
"cryptography>=50",
|
|
||||||
"dateparser~=1.4",
|
"dateparser~=1.4",
|
||||||
# WARNING: django does not use semver.
|
# WARNING: django does not use semver.
|
||||||
# Only patch versions are guaranteed to not introduce breaking changes.
|
# Only patch versions are guaranteed to not introduce breaking changes.
|
||||||
@@ -47,7 +46,6 @@ dependencies = [
|
|||||||
"flower>=2.0.1,<2.3",
|
"flower>=2.0.1,<2.3",
|
||||||
"gotenberg-client[httpx]~=1.0",
|
"gotenberg-client[httpx]~=1.0",
|
||||||
"httpx-oauth~=0.17",
|
"httpx-oauth~=0.17",
|
||||||
"humanize>=4.15",
|
|
||||||
"ijson>=3.5.1",
|
"ijson>=3.5.1",
|
||||||
"imap-tools>=1.14,<1.16",
|
"imap-tools>=1.14,<1.16",
|
||||||
"jinja2~=3.1.6",
|
"jinja2~=3.1.6",
|
||||||
@@ -58,13 +56,10 @@ dependencies = [
|
|||||||
"llama-index-embeddings-openai-like>=0.2.2",
|
"llama-index-embeddings-openai-like>=0.2.2",
|
||||||
"llama-index-llms-ollama>=0.9.1",
|
"llama-index-llms-ollama>=0.9.1",
|
||||||
"llama-index-llms-openai-like>=0.7.1",
|
"llama-index-llms-openai-like>=0.7.1",
|
||||||
"lxml>=6.1",
|
|
||||||
"ocrmypdf[heic]>=17.12,<17.13",
|
"ocrmypdf[heic]>=17.12,<17.13",
|
||||||
"ollama>=0.6.1",
|
|
||||||
"openai>=2.48",
|
"openai>=2.48",
|
||||||
"pathvalidate~=3.3.1",
|
"pathvalidate~=3.3.1",
|
||||||
"pdf2image~=1.17.0",
|
"pdf2image~=1.17.0",
|
||||||
"pikepdf>=10.13",
|
|
||||||
"python-dateutil~=2.9.0",
|
"python-dateutil~=2.9.0",
|
||||||
"python-dotenv~=1.2.1",
|
"python-dotenv~=1.2.1",
|
||||||
"python-gnupg~=0.5.4",
|
"python-gnupg~=0.5.4",
|
||||||
@@ -76,7 +71,7 @@ dependencies = [
|
|||||||
"scikit-learn~=1.9.0",
|
"scikit-learn~=1.9.0",
|
||||||
"sentence-transformers>=5.6.1",
|
"sentence-transformers>=5.6.1",
|
||||||
"setproctitle~=1.3.4",
|
"setproctitle~=1.3.4",
|
||||||
"sqlite-vec==0.1.10+paperless.3",
|
"sqlite-vec==0.1.9",
|
||||||
"tantivy~=0.26.0",
|
"tantivy~=0.26.0",
|
||||||
"tika-client[httpx]~=1.0",
|
"tika-client[httpx]~=1.0",
|
||||||
"torch>=2.13,<2.15",
|
"torch>=2.13,<2.15",
|
||||||
@@ -91,9 +86,9 @@ mariadb = [
|
|||||||
"mysqlclient>=2.2.7,<2.4",
|
"mysqlclient>=2.2.7,<2.4",
|
||||||
]
|
]
|
||||||
postgres = [
|
postgres = [
|
||||||
"psycopg[c,pool]==3.3.8",
|
"psycopg[c,pool]==3.3.4",
|
||||||
# Direct dependency for proper resolution of the pre-built wheels
|
# Direct dependency for proper resolution of the pre-built wheels
|
||||||
"psycopg-c==3.3.8",
|
"psycopg-c==3.3.4",
|
||||||
"psycopg-pool==3.3.3",
|
"psycopg-pool==3.3.3",
|
||||||
]
|
]
|
||||||
webserver = [
|
webserver = [
|
||||||
@@ -111,7 +106,7 @@ docs = [
|
|||||||
]
|
]
|
||||||
lint = [
|
lint = [
|
||||||
"prek>=0.4.11,<0.6",
|
"prek>=0.4.11,<0.6",
|
||||||
"ruff~=0.17.2",
|
"ruff~=0.16.1",
|
||||||
]
|
]
|
||||||
testing = [
|
testing = [
|
||||||
"daphne",
|
"daphne",
|
||||||
@@ -156,24 +151,17 @@ typing = [
|
|||||||
required-version = ">=0.9.0"
|
required-version = ">=0.9.0"
|
||||||
prerelease = "disallow"
|
prerelease = "disallow"
|
||||||
environments = [
|
environments = [
|
||||||
"sys_platform == 'darwin' and platform_machine == 'arm64' and platform_python_implementation == 'CPython'",
|
"sys_platform == 'darwin'",
|
||||||
"sys_platform == 'linux' and platform_machine == 'aarch64' and platform_python_implementation == 'CPython'",
|
"sys_platform == 'linux'",
|
||||||
"sys_platform == 'linux' and platform_machine == 'x86_64' and platform_python_implementation == 'CPython'",
|
|
||||||
]
|
]
|
||||||
package = false
|
package = false
|
||||||
[tool.uv.sources]
|
[tool.uv.sources]
|
||||||
# Markers are chosen to select these almost exclusively when building the Docker image
|
# Markers are chosen to select these almost exclusively when building the Docker image
|
||||||
psycopg-c = [
|
psycopg-c = [
|
||||||
{ url = "https://github.com/paperless-ngx/builder/releases/download/psycopg-trixie-3.3.8/psycopg_c-3.3.8-cp312-cp312-manylinux_2_38_x86_64.whl", marker = "sys_platform == 'linux' and platform_machine == 'x86_64' and python_version == '3.12'" },
|
{ url = "https://github.com/paperless-ngx/builder/releases/download/psycopg-trixie-3.3.4/psycopg_c-3.3.4-cp312-cp312-linux_x86_64.whl", marker = "sys_platform == 'linux' and platform_machine == 'x86_64' and python_version == '3.12'" },
|
||||||
{ url = "https://github.com/paperless-ngx/builder/releases/download/psycopg-trixie-3.3.8/psycopg_c-3.3.8-cp312-cp312-manylinux_2_38_aarch64.whl", marker = "sys_platform == 'linux' and platform_machine == 'aarch64' and python_version == '3.12'" },
|
{ url = "https://github.com/paperless-ngx/builder/releases/download/psycopg-trixie-3.3.4/psycopg_c-3.3.4-cp312-cp312-linux_aarch64.whl", marker = "sys_platform == 'linux' and platform_machine == 'aarch64' and python_version == '3.12'" },
|
||||||
{ url = "https://github.com/paperless-ngx/builder/releases/download/psycopg-trixie-3.3.8/psycopg_c-3.3.8-cp314-cp314-manylinux_2_38_x86_64.whl", marker = "sys_platform == 'linux' and platform_machine == 'x86_64' and python_version == '3.14'" },
|
{ url = "https://github.com/paperless-ngx/builder/releases/download/psycopg-trixie-3.3.4/psycopg_c-3.3.4-cp314-cp314-linux_x86_64.whl", marker = "sys_platform == 'linux' and platform_machine == 'x86_64' and python_version == '3.14'" },
|
||||||
{ url = "https://github.com/paperless-ngx/builder/releases/download/psycopg-trixie-3.3.8/psycopg_c-3.3.8-cp314-cp314-manylinux_2_38_aarch64.whl", marker = "sys_platform == 'linux' and platform_machine == 'aarch64' and python_version == '3.14'" },
|
{ url = "https://github.com/paperless-ngx/builder/releases/download/psycopg-trixie-3.3.4/psycopg_c-3.3.4-cp314-cp314-linux_aarch64.whl", marker = "sys_platform == 'linux' and platform_machine == 'aarch64' and python_version == '3.14'" },
|
||||||
]
|
|
||||||
# Patched sqlite-vec builds
|
|
||||||
sqlite-vec = [
|
|
||||||
{ url = "https://github.com/paperless-ngx/builder/releases/download/sqlite-vec-0.1.10%2Bpaperless.3/sqlite_vec-0.1.10%2Bpaperless.3-py3-none-manylinux_2_29_x86_64.whl", marker = "sys_platform == 'linux' and platform_machine == 'x86_64'" },
|
|
||||||
{ url = "https://github.com/paperless-ngx/builder/releases/download/sqlite-vec-0.1.10%2Bpaperless.3/sqlite_vec-0.1.10%2Bpaperless.3-py3-none-manylinux_2_29_aarch64.whl", marker = "sys_platform == 'linux' and platform_machine == 'aarch64'" },
|
|
||||||
{ url = "https://github.com/paperless-ngx/builder/releases/download/sqlite-vec-0.1.10%2Bpaperless.3/sqlite_vec-0.1.10%2Bpaperless.3-py3-none-macosx_11_0_arm64.whl", marker = "sys_platform == 'darwin' and platform_machine == 'arm64'" },
|
|
||||||
]
|
]
|
||||||
torch = [
|
torch = [
|
||||||
{ index = "pytorch-cpu" },
|
{ index = "pytorch-cpu" },
|
||||||
|
|||||||
+571
-1812
File diff suppressed because it is too large.
Load diff
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "paperless-ngx-ui",
|
"name": "paperless-ngx-ui",
|
||||||
"version": "3.5.1",
|
"version": "3.4.2",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"preinstall": "npx only-allow pnpm",
|
"preinstall": "npx only-allow pnpm",
|
||||||
"ng": "ng",
|
"ng": "ng",
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ import { DocumentDetailComponent } from './components/document-detail/document-d
|
|||||||
import { DocumentListComponent } from './components/document-list/document-list.component'
|
import { DocumentListComponent } from './components/document-list/document-list.component'
|
||||||
import { DocumentAttributesComponent } from './components/manage/document-attributes/document-attributes.component'
|
import { DocumentAttributesComponent } from './components/manage/document-attributes/document-attributes.component'
|
||||||
import { MailComponent } from './components/manage/mail/mail.component'
|
import { MailComponent } from './components/manage/mail/mail.component'
|
||||||
import { OcrTemplatesComponent } from './components/manage/ocr-templates/ocr-templates.component'
|
|
||||||
import { SavedViewsComponent } from './components/manage/saved-views/saved-views.component'
|
import { SavedViewsComponent } from './components/manage/saved-views/saved-views.component'
|
||||||
import { ShareLinksComponent } from './components/manage/share-links/share-links.component'
|
import { ShareLinksComponent } from './components/manage/share-links/share-links.component'
|
||||||
import { WorkflowsComponent } from './components/manage/workflows/workflows.component'
|
import { WorkflowsComponent } from './components/manage/workflows/workflows.component'
|
||||||
@@ -276,18 +275,6 @@ export const routes: Routes = [
|
|||||||
componentName: 'WorkflowsComponent',
|
componentName: 'WorkflowsComponent',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
|
||||||
path: 'ocr-templates',
|
|
||||||
component: OcrTemplatesComponent,
|
|
||||||
canActivate: [PermissionsGuard],
|
|
||||||
data: {
|
|
||||||
requiredPermission: {
|
|
||||||
action: PermissionAction.View,
|
|
||||||
type: PermissionType.OcrTemplate,
|
|
||||||
},
|
|
||||||
componentName: 'OcrTemplatesComponent',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
path: 'mail',
|
path: 'mail',
|
||||||
component: MailComponent,
|
component: MailComponent,
|
||||||
|
|||||||
@@ -227,12 +227,6 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="row">
|
|
||||||
<div class="col">
|
|
||||||
<pngx-input-check i18n-title title="Show nested tags with their parents" i18n-hint hint="Child tags are shown together with their parent tags, instead of separately." formControlName="tagsShowHierarchy"></pngx-input-check>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<h5 class="mt-3" i18n>Document editing</h5>
|
<h5 class="mt-3" i18n>Document editing</h5>
|
||||||
<div class="row">
|
<div class="row">
|
||||||
<div class="col">
|
<div class="col">
|
||||||
|
|||||||
@@ -305,7 +305,7 @@ describe('SettingsComponent', () => {
|
|||||||
expect(toastErrorSpy).toHaveBeenCalled()
|
expect(toastErrorSpy).toHaveBeenCalled()
|
||||||
expect(storeSpy).toHaveBeenCalled()
|
expect(storeSpy).toHaveBeenCalled()
|
||||||
expect(appearanceSettingsSpy).not.toHaveBeenCalled()
|
expect(appearanceSettingsSpy).not.toHaveBeenCalled()
|
||||||
expect(setSpy).toHaveBeenCalledTimes(34)
|
expect(setSpy).toHaveBeenCalledTimes(33)
|
||||||
expect(setSpy).toHaveBeenCalledWith(SETTINGS_KEYS.SIDEBAR_HIDDEN_ITEMS, [
|
expect(setSpy).toHaveBeenCalledWith(SETTINGS_KEYS.SIDEBAR_HIDDEN_ITEMS, [
|
||||||
HideableSidebarItemID.Workflows,
|
HideableSidebarItemID.Workflows,
|
||||||
])
|
])
|
||||||
|
|||||||
@@ -113,7 +113,6 @@ const sidebarItemLabels: Record<HideableSidebarItemID, string> = {
|
|||||||
[HideableSidebarItemID.SavedViews]: $localize`Saved Views`,
|
[HideableSidebarItemID.SavedViews]: $localize`Saved Views`,
|
||||||
[HideableSidebarItemID.ShareLinks]: $localize`Share Links`,
|
[HideableSidebarItemID.ShareLinks]: $localize`Share Links`,
|
||||||
[HideableSidebarItemID.Workflows]: $localize`Workflows`,
|
[HideableSidebarItemID.Workflows]: $localize`Workflows`,
|
||||||
[HideableSidebarItemID.OcrTemplates]: $localize`OCR Templates`,
|
|
||||||
[HideableSidebarItemID.Mail]: $localize`Mail`,
|
[HideableSidebarItemID.Mail]: $localize`Mail`,
|
||||||
[HideableSidebarItemID.Documentation]: $localize`Documentation`,
|
[HideableSidebarItemID.Documentation]: $localize`Documentation`,
|
||||||
}
|
}
|
||||||
@@ -164,7 +163,6 @@ export class SettingsComponent
|
|||||||
bulkEditConfirmationDialogs: new FormControl(null),
|
bulkEditConfirmationDialogs: new FormControl(null),
|
||||||
bulkEditApplyOnClose: new FormControl(null),
|
bulkEditApplyOnClose: new FormControl(null),
|
||||||
documentListItemPerPage: new FormControl(null),
|
documentListItemPerPage: new FormControl(null),
|
||||||
tagsShowHierarchy: new FormControl(null),
|
|
||||||
slimSidebarEnabled: new FormControl(null),
|
slimSidebarEnabled: new FormControl(null),
|
||||||
sidebarHiddenItems: new FormControl<HideableSidebarItemID[]>([]),
|
sidebarHiddenItems: new FormControl<HideableSidebarItemID[]>([]),
|
||||||
darkModeUseSystem: new FormControl(null),
|
darkModeUseSystem: new FormControl(null),
|
||||||
@@ -344,7 +342,6 @@ export class SettingsComponent
|
|||||||
bulkEditApplyOnClose: this.settings.get(
|
bulkEditApplyOnClose: this.settings.get(
|
||||||
SETTINGS_KEYS.BULK_EDIT_APPLY_ON_CLOSE
|
SETTINGS_KEYS.BULK_EDIT_APPLY_ON_CLOSE
|
||||||
),
|
),
|
||||||
tagsShowHierarchy: this.settings.get(SETTINGS_KEYS.TAGS_SHOW_HIERARCHY),
|
|
||||||
documentListItemPerPage: this.settings.get(
|
documentListItemPerPage: this.settings.get(
|
||||||
SETTINGS_KEYS.DOCUMENT_LIST_SIZE
|
SETTINGS_KEYS.DOCUMENT_LIST_SIZE
|
||||||
),
|
),
|
||||||
@@ -610,10 +607,6 @@ export class SettingsComponent
|
|||||||
SETTINGS_KEYS.DEFAULT_PERMS_EDIT_GROUPS,
|
SETTINGS_KEYS.DEFAULT_PERMS_EDIT_GROUPS,
|
||||||
this.settingsForm.value.defaultPermsEditGroups
|
this.settingsForm.value.defaultPermsEditGroups
|
||||||
)
|
)
|
||||||
this.settings.set(
|
|
||||||
SETTINGS_KEYS.TAGS_SHOW_HIERARCHY,
|
|
||||||
this.settingsForm.value.tagsShowHierarchy
|
|
||||||
)
|
|
||||||
this.settings.set(
|
this.settings.set(
|
||||||
SETTINGS_KEYS.DOCUMENT_EDITING_REMOVE_INBOX_TAGS,
|
SETTINGS_KEYS.DOCUMENT_EDITING_REMOVE_INBOX_TAGS,
|
||||||
this.settingsForm.value.documentEditingRemoveInboxTags
|
this.settingsForm.value.documentEditingRemoveInboxTags
|
||||||
|
|||||||
@@ -175,13 +175,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
<td class="overflow-auto name-col">
|
<td class="overflow-auto name-col">
|
||||||
@let documentCount = taskDocumentCount(task);
|
<div>{{ taskDisplayName(task) }}</div>
|
||||||
<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 class="small text-muted">
|
<div class="small text-muted">
|
||||||
@if (taskShowsSeparateTypeLabel(task)) {
|
@if (taskShowsSeparateTypeLabel(task)) {
|
||||||
<span class="me-2">{{ task.task_type_display }}</span>
|
<span class="me-2">{{ task.task_type_display }}</span>
|
||||||
|
|||||||
@@ -895,117 +895,6 @@ describe('TasksComponent', () => {
|
|||||||
expect(sanityTaskRow.nativeElement.textContent).toContain('System')
|
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', () => {
|
it('should filter tasks by result', () => {
|
||||||
component.setSection(TaskSection.NeedsAttention)
|
component.setSection(TaskSection.NeedsAttention)
|
||||||
component.filterTargetID = 1
|
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 { CustomDatePipe } from 'src/app/pipes/custom-date.pipe'
|
||||||
import { TasksService } from 'src/app/services/tasks.service'
|
import { TasksService } from 'src/app/services/tasks.service'
|
||||||
import { ToastService } from 'src/app/services/toast.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 { ConfirmDialogComponent } from '../../common/confirm-dialog/confirm-dialog.component'
|
||||||
import { PageHeaderComponent } from '../../common/page-header/page-header.component'
|
import { PageHeaderComponent } from '../../common/page-header/page-header.component'
|
||||||
import { LoadingComponentWithPermissions } from '../../loading-component/loading.component'
|
import { LoadingComponentWithPermissions } from '../../loading-component/loading.component'
|
||||||
@@ -418,30 +414,11 @@ export class TasksComponent
|
|||||||
}
|
}
|
||||||
|
|
||||||
taskDisplayName(task: PaperlessTask): string {
|
taskDisplayName(task: PaperlessTask): string {
|
||||||
const filename = task.input_data?.filename?.toString()
|
return task.input_data?.filename?.toString() || task.task_type_display
|
||||||
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
|
|
||||||
}
|
}
|
||||||
|
|
||||||
taskShowsSeparateTypeLabel(task: PaperlessTask): boolean {
|
taskShowsSeparateTypeLabel(task: PaperlessTask): boolean {
|
||||||
return (
|
return this.taskDisplayName(task) !== task.task_type_display
|
||||||
!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
|
|
||||||
}
|
}
|
||||||
|
|
||||||
taskResultMessage(task: PaperlessTask): string | null {
|
taskResultMessage(task: PaperlessTask): string | null {
|
||||||
@@ -469,15 +446,6 @@ export class TasksComponent
|
|||||||
return errorMessage
|
return errorMessage
|
||||||
}
|
}
|
||||||
|
|
||||||
if (
|
|
||||||
task.status === PaperlessTaskStatus.Success &&
|
|
||||||
this.taskOperationLabel(task)
|
|
||||||
) {
|
|
||||||
return documentOperationHasFollowUpTasks(task.input_data?.operation)
|
|
||||||
? $localize`Submitted for processing`
|
|
||||||
: $localize`Completed`
|
|
||||||
}
|
|
||||||
|
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -289,17 +289,6 @@
|
|||||||
<pngx-input-switch class="position-absolute top-50 end-0 translate-middle-y me-1" [class.d-none]="slimSidebarEnabled || slimSidebarAnimating()" [compact]="true" title="Workflows" i18n-title [ngModel]="!settingsService.sidebarItemIsHidden(HideableSidebarItemID.Workflows)" (ngModelChange)="toggleSidebarItem(HideableSidebarItemID.Workflows, $event)"></pngx-input-switch>
|
<pngx-input-switch class="position-absolute top-50 end-0 translate-middle-y me-1" [class.d-none]="slimSidebarEnabled || slimSidebarAnimating()" [compact]="true" title="Workflows" i18n-title [ngModel]="!settingsService.sidebarItemIsHidden(HideableSidebarItemID.Workflows)" (ngModelChange)="toggleSidebarItem(HideableSidebarItemID.Workflows, $event)"></pngx-input-switch>
|
||||||
}
|
}
|
||||||
</li>
|
</li>
|
||||||
<li class="nav-item app-link position-relative" [class.d-none]="settingsService.sidebarItemIsHidden(HideableSidebarItemID.OcrTemplates) && !settingsService.organizingSidebarItems()"
|
|
||||||
*pngxIfPermissions="{ action: PermissionAction.View, type: PermissionType.OcrTemplate }">
|
|
||||||
<a class="nav-link" [class.opacity-50]="settingsService.sidebarItemIsHidden(HideableSidebarItemID.OcrTemplates)" [class.pe-5]="settingsService.organizingSidebarItems() && !slimSidebarEnabled && !slimSidebarAnimating()" routerLink="ocr-templates" routerLinkActive="active" (click)="closeMenu()"
|
|
||||||
ngbPopover="OCR Templates" i18n-ngbPopover [disablePopover]="!slimSidebarPopoversEnabled" placement="end"
|
|
||||||
container="body" triggers="mouseenter:mouseleave" popoverClass="popover-slim">
|
|
||||||
<pngx-bs-icon class="me-2" name="bounding-box-circles"></pngx-bs-icon><span class="nav-link-label"><ng-container i18n>OCR Templates</ng-container></span>
|
|
||||||
</a>
|
|
||||||
@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="OCR Templates" i18n-title [ngModel]="!settingsService.sidebarItemIsHidden(HideableSidebarItemID.OcrTemplates)" (ngModelChange)="toggleSidebarItem(HideableSidebarItemID.OcrTemplates, $event)"></pngx-input-switch>
|
|
||||||
}
|
|
||||||
</li>
|
|
||||||
<li class="nav-item app-link position-relative" [class.d-none]="settingsService.sidebarItemIsHidden(HideableSidebarItemID.Mail) && !settingsService.organizingSidebarItems()" *pngxIfPermissions="{ action: PermissionAction.View, type: PermissionType.MailAccount }"
|
<li class="nav-item app-link position-relative" [class.d-none]="settingsService.sidebarItemIsHidden(HideableSidebarItemID.Mail) && !settingsService.organizingSidebarItems()" *pngxIfPermissions="{ action: PermissionAction.View, type: PermissionType.MailAccount }"
|
||||||
tourAnchor="tour.mail">
|
tourAnchor="tour.mail">
|
||||||
<a class="nav-link" [class.opacity-50]="settingsService.sidebarItemIsHidden(HideableSidebarItemID.Mail)" [class.pe-5]="settingsService.organizingSidebarItems() && !slimSidebarEnabled && !slimSidebarAnimating()" routerLink="mail" routerLinkActive="active" (click)="closeMenu()" ngbPopover="Mail"
|
<a class="nav-link" [class.opacity-50]="settingsService.sidebarItemIsHidden(HideableSidebarItemID.Mail)" [class.pe-5]="settingsService.organizingSidebarItems() && !slimSidebarEnabled && !slimSidebarAnimating()" routerLink="mail" routerLinkActive="active" (click)="closeMenu()" ngbPopover="Mail"
|
||||||
@@ -372,9 +361,8 @@
|
|||||||
</a>
|
</a>
|
||||||
</li>
|
</li>
|
||||||
}
|
}
|
||||||
<li class="nav-item mt-2 position-relative" [class.d-none]="settingsService.sidebarItemIsHidden(HideableSidebarItemID.Documentation) && !settingsService.organizingSidebarItems()"
|
<li class="nav-item mt-2 position-relative" [class.d-none]="settingsService.sidebarItemIsHidden(HideableSidebarItemID.Documentation) && !settingsService.organizingSidebarItems()" tourAnchor="tour.outro">
|
||||||
[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.opacity-50]="settingsService.sidebarItemIsHidden(HideableSidebarItemID.Documentation)" [class.pe-5]="settingsService.organizingSidebarItems() && !slimSidebarEnabled && !slimSidebarAnimating()"
|
||||||
<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()"
|
|
||||||
target="_blank" rel="noopener noreferrer" href="https://docs.paperless-ngx.com" ngbPopover="Documentation"
|
target="_blank" rel="noopener noreferrer" href="https://docs.paperless-ngx.com" ngbPopover="Documentation"
|
||||||
i18n-ngbPopover [disablePopover]="!slimSidebarPopoversEnabled" placement="end" container="body"
|
i18n-ngbPopover [disablePopover]="!slimSidebarPopoversEnabled" placement="end" container="body"
|
||||||
triggers="mouseenter:mouseleave" popoverClass="popover-slim">
|
triggers="mouseenter:mouseleave" popoverClass="popover-slim">
|
||||||
@@ -383,35 +371,23 @@
|
|||||||
@if (settingsService.organizingSidebarItems()) {
|
@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>
|
<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>
|
||||||
<li class="nav-item" [class.visually-hidden]="slimSidebarEnabled">
|
<li class="nav-item" [class.visually-hidden]="slimSidebarEnabled">
|
||||||
<div class="text-muted small d-flex align-items-center flex-wrap nav-label">
|
<div class="text-muted small d-flex align-items-center flex-wrap nav-label">
|
||||||
<div class="me-2">
|
<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 }}
|
{{ versionString }}
|
||||||
</button>
|
</a>
|
||||||
@if (settingsService.unseenReleasesSince()) {
|
|
||||||
<div class="btn-group ms-2 align-baseline">
|
|
||||||
<button type="button" class="btn btn-whats-new rounded-start-pill smaller py-1 px-2 fw-bold lh-sm" (click)="showReleaseNotes()"
|
|
||||||
title="See what's new in this version" i18n-title i18n>New</button>
|
|
||||||
<button type="button" class="btn btn-whats-new rounded-end-pill smaller py-1 px-1 lh-sm d-flex align-items-center" (click)="dismissReleaseNotes()"
|
|
||||||
title="Dismiss" i18n-title aria-label="Dismiss" i18n-aria-label>
|
|
||||||
<pngx-bs-icon name="x" class="d-flex" width="1em" height="1em"></pngx-bs-icon>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
</div>
|
</div>
|
||||||
@if (!settingsService.updateCheckingIsSet || appRemoteVersion()) {
|
@if (!settingsService.updateCheckingIsSet || appRemoteVersion()) {
|
||||||
<div class="version-check d-flex align-items-center">
|
<div class="version-check d-flex align-items-center">
|
||||||
|
<ng-template #updateAvailablePopContent>
|
||||||
|
<span class="small">Paperless-ngx {{ appRemoteVersion().version }} <ng-container i18n>is
|
||||||
|
available.</ng-container><br /><ng-container i18n>Click to view.</ng-container></span>
|
||||||
|
</ng-template>
|
||||||
<ng-template #updateCheckingNotEnabledPopContent>
|
<ng-template #updateCheckingNotEnabledPopContent>
|
||||||
<p class="small mb-2">
|
<p class="small mb-2">
|
||||||
<ng-container i18n>Paperless-ngx can automatically check for updates</ng-container>
|
<ng-container i18n>Paperless-ngx can automatically check for updates</ng-container>
|
||||||
@@ -428,13 +404,15 @@
|
|||||||
</ng-template>
|
</ng-template>
|
||||||
@if (settingsService.updateCheckingIsSet) {
|
@if (settingsService.updateCheckingIsSet) {
|
||||||
@if (appRemoteVersion().update_available) {
|
@if (appRemoteVersion().update_available) {
|
||||||
<button type="button" class="bg-transparent border-0 p-0 small text-primary" (click)="showAvailableReleaseNotes()"
|
<a class="small text-decoration-none" target="_blank" rel="noopener noreferrer"
|
||||||
title="Paperless-ngx {{ appRemoteVersion().version }} is available" i18n-title>
|
href="https://github.com/paperless-ngx/paperless-ngx/releases"
|
||||||
|
[ngbPopover]="updateAvailablePopContent" popoverClass="shadow" triggers="mouseenter:mouseleave"
|
||||||
|
container="body">
|
||||||
<pngx-bs-icon width="1.2em" height="1.2em" name="info-circle" class="me-1"></pngx-bs-icon>
|
<pngx-bs-icon width="1.2em" height="1.2em" name="info-circle" class="me-1"></pngx-bs-icon>
|
||||||
@if (appRemoteVersion()?.update_available) {
|
@if (appRemoteVersion()?.update_available) {
|
||||||
<ng-container i18n>Update available</ng-container>
|
<ng-container i18n>Update available</ng-container>
|
||||||
}
|
}
|
||||||
</button>
|
</a>
|
||||||
}
|
}
|
||||||
} @else {
|
} @else {
|
||||||
<a *pngxIfPermissions="{ action: PermissionAction.Change, type: PermissionType.UISettings }" class="small text-decoration-none" routerLink="/settings" fragment="update-checking" aria-label="Configure update checking" i18n-aria-label
|
<a *pngxIfPermissions="{ action: PermissionAction.Change, type: PermissionType.UISettings }" class="small text-decoration-none" routerLink="/settings" fragment="update-checking" aria-label="Configure update checking" i18n-aria-label
|
||||||
|
|||||||
@@ -700,15 +700,3 @@ main {
|
|||||||
.smaller {
|
.smaller {
|
||||||
font-size: 0.75rem;
|
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 { SavedViewService } from 'src/app/services/rest/saved-view.service'
|
||||||
import { SearchService } from 'src/app/services/rest/search.service'
|
import { SearchService } from 'src/app/services/rest/search.service'
|
||||||
import { SettingsService } from 'src/app/services/settings.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 { TasksService } from 'src/app/services/tasks.service'
|
||||||
import { ToastService } from 'src/app/services/toast.service'
|
import { ToastService } from 'src/app/services/toast.service'
|
||||||
import { UploadDocumentsService } from 'src/app/services/upload-documents.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 { ProfileEditDialogComponent } from '../common/profile-edit-dialog/profile-edit-dialog.component'
|
||||||
import { UploadStatusTrayComponent } from '../common/upload-status-tray/upload-status-tray.component'
|
import { UploadStatusTrayComponent } from '../common/upload-status-tray/upload-status-tray.component'
|
||||||
import { DocumentDetailComponent } from '../document-detail/document-detail.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 { AppFrameComponent } from './app-frame.component'
|
||||||
import { GlobalSearchComponent } from './global-search/global-search.component'
|
import { GlobalSearchComponent } from './global-search/global-search.component'
|
||||||
|
|
||||||
@@ -200,14 +198,14 @@ describe('AppFrameComponent', () => {
|
|||||||
fixture.detectChanges()
|
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 list = TestBed.inject(DocumentListViewService)
|
||||||
const reload = jest.spyOn(list, 'reload').mockImplementation(() => {})
|
const reload = jest.spyOn(list, 'reload').mockImplementation(() => {})
|
||||||
jest.spyOn(list, 'reduceSelectionToFilter').mockImplementation(() => {})
|
jest.spyOn(list, 'reduceSelectionToFilter').mockImplementation(() => {})
|
||||||
const tasksReload = jest
|
const tasksReload = jest
|
||||||
.spyOn(tasksService, 'reload')
|
.spyOn(tasksService, 'reload')
|
||||||
.mockImplementation(() => {})
|
.mockImplementation(() => {})
|
||||||
const success = jest.spyOn(toastService, 'show')
|
const success = jest.spyOn(toastService, 'showSuccess')
|
||||||
const refresh = jest
|
const refresh = jest
|
||||||
.spyOn(openDocumentsService, 'refreshDocument')
|
.spyOn(openDocumentsService, 'refreshDocument')
|
||||||
.mockImplementation(() => {})
|
.mockImplementation(() => {})
|
||||||
@@ -232,12 +230,7 @@ describe('AppFrameComponent', () => {
|
|||||||
expect(refresh).toHaveBeenCalledWith(document.id)
|
expect(refresh).toHaveBeenCalledWith(document.id)
|
||||||
expect(maybeRefreshSpy).toHaveBeenCalledTimes(1)
|
expect(maybeRefreshSpy).toHaveBeenCalledTimes(1)
|
||||||
expect(tasksReload).toHaveBeenCalledTimes(1)
|
expect(tasksReload).toHaveBeenCalledTimes(1)
|
||||||
expect(success).toHaveBeenCalledWith(
|
expect(success).toHaveBeenCalledWith('Bulk operation completed.')
|
||||||
expect.objectContaining({
|
|
||||||
id: 'task-bulk-task',
|
|
||||||
content: "Operation 'Set permissions' completed.",
|
|
||||||
})
|
|
||||||
)
|
|
||||||
fixture.destroy()
|
fixture.destroy()
|
||||||
bulkEvents.next({
|
bulkEvents.next({
|
||||||
task_id: 'bulk-task',
|
task_id: 'bulk-task',
|
||||||
@@ -252,14 +245,14 @@ describe('AppFrameComponent', () => {
|
|||||||
const reload = jest.spyOn(list, 'reload').mockImplementation(() => {})
|
const reload = jest.spyOn(list, 'reload').mockImplementation(() => {})
|
||||||
jest.spyOn(list, 'reduceSelectionToFilter').mockImplementation(() => {})
|
jest.spyOn(list, 'reduceSelectionToFilter').mockImplementation(() => {})
|
||||||
jest.spyOn(tasksService, 'reload').mockImplementation(() => {})
|
jest.spyOn(tasksService, 'reload').mockImplementation(() => {})
|
||||||
const error = jest.spyOn(toastService, 'show')
|
const error = jest.spyOn(toastService, 'showError')
|
||||||
const success = jest.spyOn(toastService, 'showSuccess')
|
const success = jest.spyOn(toastService, 'showSuccess')
|
||||||
for (const status of [
|
for (const status of [
|
||||||
PaperlessTaskStatus.Failure,
|
PaperlessTaskStatus.Failure,
|
||||||
PaperlessTaskStatus.Revoked,
|
PaperlessTaskStatus.Revoked,
|
||||||
]) {
|
]) {
|
||||||
bulkEvents.next({
|
bulkEvents.next({
|
||||||
task_id: `${status}-task`,
|
task_id: 'bulk-task',
|
||||||
operation: 'set_permissions',
|
operation: 'set_permissions',
|
||||||
status,
|
status,
|
||||||
error:
|
error:
|
||||||
@@ -269,36 +262,11 @@ describe('AppFrameComponent', () => {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
expect(reload).toHaveBeenCalledTimes(2)
|
expect(reload).toHaveBeenCalledTimes(2)
|
||||||
|
expect(error).toHaveBeenCalledWith(expect.any(String), 'Could not update')
|
||||||
expect(error).toHaveBeenCalledWith(
|
expect(error).toHaveBeenCalledWith(
|
||||||
expect.objectContaining({
|
'Bulk operation revoked.',
|
||||||
content:
|
'Task expired before execution.'
|
||||||
"Operation 'Set permissions' failed. Some changes may already have been applied.",
|
|
||||||
error: 'Could not update',
|
|
||||||
})
|
|
||||||
)
|
)
|
||||||
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()
|
expect(success).not.toHaveBeenCalled()
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -405,7 +373,6 @@ describe('AppFrameComponent', () => {
|
|||||||
HideableSidebarItemID.Dashboard,
|
HideableSidebarItemID.Dashboard,
|
||||||
HideableSidebarItemID.Workflows,
|
HideableSidebarItemID.Workflows,
|
||||||
HideableSidebarItemID.ShareLinks,
|
HideableSidebarItemID.ShareLinks,
|
||||||
HideableSidebarItemID.OcrTemplates,
|
|
||||||
])
|
])
|
||||||
fixture.detectChanges()
|
fixture.detectChanges()
|
||||||
|
|
||||||
@@ -421,10 +388,6 @@ describe('AppFrameComponent', () => {
|
|||||||
fixture.nativeElement.querySelector('[routerLink="share-links"]')
|
fixture.nativeElement.querySelector('[routerLink="share-links"]')
|
||||||
.parentElement.classList
|
.parentElement.classList
|
||||||
).toContain('d-none')
|
).toContain('d-none')
|
||||||
expect(
|
|
||||||
fixture.nativeElement.querySelector('[routerLink="ocr-templates"]')
|
|
||||||
.parentElement.classList
|
|
||||||
).toContain('d-none')
|
|
||||||
expect(
|
expect(
|
||||||
fixture.nativeElement.querySelector('[routerLink="mail"]').parentElement
|
fixture.nativeElement.querySelector('[routerLink="mail"]').parentElement
|
||||||
.classList
|
.classList
|
||||||
@@ -437,21 +400,12 @@ describe('AppFrameComponent', () => {
|
|||||||
])
|
])
|
||||||
settingsService.sidebarHiddenItemsEditing.set([
|
settingsService.sidebarHiddenItemsEditing.set([
|
||||||
HideableSidebarItemID.Dashboard,
|
HideableSidebarItemID.Dashboard,
|
||||||
HideableSidebarItemID.OcrTemplates,
|
|
||||||
])
|
])
|
||||||
fixture.detectChanges()
|
fixture.detectChanges()
|
||||||
|
|
||||||
expect(
|
expect(
|
||||||
fixture.nativeElement.querySelectorAll('pngx-input-switch').length
|
fixture.nativeElement.querySelectorAll('pngx-input-switch').length
|
||||||
).toBe(7)
|
).toBe(6)
|
||||||
const ocrTemplatesLink = fixture.nativeElement.querySelector(
|
|
||||||
'[routerLink="ocr-templates"]'
|
|
||||||
)
|
|
||||||
expect(ocrTemplatesLink.parentElement.classList).not.toContain('d-none')
|
|
||||||
expect(ocrTemplatesLink.classList).toContain('opacity-50')
|
|
||||||
expect(
|
|
||||||
ocrTemplatesLink.parentElement.querySelector('pngx-input-switch')
|
|
||||||
).not.toBeNull()
|
|
||||||
expect(
|
expect(
|
||||||
fixture.nativeElement.querySelector('[routerLink="dashboard"]')
|
fixture.nativeElement.querySelector('[routerLink="dashboard"]')
|
||||||
.parentElement.classList
|
.parentElement.classList
|
||||||
@@ -710,131 +664,6 @@ describe('AppFrameComponent', () => {
|
|||||||
expect(maybeRefreshSpy).toHaveBeenCalled()
|
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 dismiss new release pill without opening release notes', () => {
|
|
||||||
settingsService.set(SETTINGS_KEYS.VERSION, '3.5.1')
|
|
||||||
settingsService.set(SETTINGS_KEYS.WHATS_NEW_LAST_SEEN_VERSION, '3.4.2')
|
|
||||||
fixture.detectChanges()
|
|
||||||
const modalSpy = jest.spyOn(modalService, 'open')
|
|
||||||
|
|
||||||
fixture.debugElement
|
|
||||||
.query(By.css('button[aria-label="Dismiss"]'))
|
|
||||||
.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(modalSpy).not.toHaveBeenCalled()
|
|
||||||
expect(
|
|
||||||
fixture.debugElement.query(By.css('button[aria-label="Dismiss"]'))
|
|
||||||
).toBeNull()
|
|
||||||
})
|
|
||||||
|
|
||||||
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 open available release notes from update available', () => {
|
|
||||||
jest
|
|
||||||
.spyOn(remoteVersionService, 'checkForUpdates')
|
|
||||||
.mockReturnValue(of({ version: '3.6.0', update_available: true }))
|
|
||||||
settingsService.set(SETTINGS_KEYS.VERSION, '3.5.1')
|
|
||||||
settingsService.set(SETTINGS_KEYS.UPDATE_CHECKING_ENABLED, true)
|
|
||||||
component.ngOnInit()
|
|
||||||
fixture.detectChanges()
|
|
||||||
const modalSpy = jest.spyOn(modalService, 'open')
|
|
||||||
const saveSpy = jest.spyOn(settingsService, 'markReleasesSeen')
|
|
||||||
|
|
||||||
const updateButton = fixture.debugElement
|
|
||||||
.queryAll(By.css('button'))
|
|
||||||
.find((b) => b.nativeElement.textContent.includes('Update available'))
|
|
||||||
expect(updateButton.nativeElement.title).toEqual(
|
|
||||||
'Paperless-ngx 3.6.0 is available'
|
|
||||||
)
|
|
||||||
updateButton.nativeElement.click()
|
|
||||||
|
|
||||||
const dialog = modalSpy.mock.results[0].value
|
|
||||||
.componentInstance as ReleaseNotesDialogComponent
|
|
||||||
expect(dialog.since()).toEqual('3.5.1')
|
|
||||||
expect(dialog.until()).toEqual('3.6.0')
|
|
||||||
expect(saveSpy).not.toHaveBeenCalled()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should save update checking chosen in the release notes dialog', () => {
|
|
||||||
const setUpdateCheckingSpy = jest
|
|
||||||
.spyOn(component, 'setUpdateChecking')
|
|
||||||
.mockImplementation(() => {})
|
|
||||||
const modalSpy = jest.spyOn(modalService, 'open')
|
|
||||||
component.showReleaseNotes()
|
|
||||||
|
|
||||||
const dialog = modalSpy.mock.results[0].value
|
|
||||||
.componentInstance as ReleaseNotesDialogComponent
|
|
||||||
dialog.updateCheckingChosen.emit(true)
|
|
||||||
expect(setUpdateCheckingSpy).toHaveBeenCalledWith(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
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', () => {
|
it('should show tasks badge for needs-attention tasks', () => {
|
||||||
jest
|
jest
|
||||||
.spyOn(tasksService, 'needsAttentionTasksCount', 'get')
|
.spyOn(tasksService, 'needsAttentionTasksCount', 'get')
|
||||||
|
|||||||
@@ -57,7 +57,6 @@ import {
|
|||||||
} from 'src/app/services/rest/remote-version.service'
|
} from 'src/app/services/rest/remote-version.service'
|
||||||
import { SavedViewService } from 'src/app/services/rest/saved-view.service'
|
import { SavedViewService } from 'src/app/services/rest/saved-view.service'
|
||||||
import { SettingsService } from 'src/app/services/settings.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 { TasksService } from 'src/app/services/tasks.service'
|
||||||
import { ToastService } from 'src/app/services/toast.service'
|
import { ToastService } from 'src/app/services/toast.service'
|
||||||
import { UploadDocumentsService } from 'src/app/services/upload-documents.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 { BrandMarkComponent } from '../common/logo/brand-mark/brand-mark.component'
|
||||||
import { LogoComponent } from '../common/logo/logo.component'
|
import { LogoComponent } from '../common/logo/logo.component'
|
||||||
import { ProfileEditDialogComponent } from '../common/profile-edit-dialog/profile-edit-dialog.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 { UploadStatusTrayComponent } from '../common/upload-status-tray/upload-status-tray.component'
|
||||||
import { DocumentDetailComponent } from '../document-detail/document-detail.component'
|
import { DocumentDetailComponent } from '../document-detail/document-detail.component'
|
||||||
import { ComponentWithPermissions } from '../with-permissions/with-permissions.component'
|
import { ComponentWithPermissions } from '../with-permissions/with-permissions.component'
|
||||||
@@ -117,7 +115,6 @@ export class AppFrameComponent
|
|||||||
settingsService = inject(SettingsService)
|
settingsService = inject(SettingsService)
|
||||||
tasksService = inject(TasksService)
|
tasksService = inject(TasksService)
|
||||||
private readonly toastService = inject(ToastService)
|
private readonly toastService = inject(ToastService)
|
||||||
private readonly taskNotifications = inject(TaskNotificationService)
|
|
||||||
private modalService = inject(NgbModal)
|
private modalService = inject(NgbModal)
|
||||||
permissionsService = inject(PermissionsService)
|
permissionsService = inject(PermissionsService)
|
||||||
private djangoMessagesService = inject(DjangoMessagesService)
|
private djangoMessagesService = inject(DjangoMessagesService)
|
||||||
@@ -185,11 +182,9 @@ export class AppFrameComponent
|
|||||||
),
|
),
|
||||||
takeUntilDestroyed(this.destroyRef)
|
takeUntilDestroyed(this.destroyRef)
|
||||||
)
|
)
|
||||||
.subscribe((result) => {
|
.subscribe(({ status, error }) => {
|
||||||
this.documentList.reload(null, false)
|
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
|
// maybe someday we can optimize to only refresh affected documents
|
||||||
this.openDocumentsService.getOpenDocuments().forEach((doc) => {
|
this.openDocumentsService.getOpenDocuments().forEach((doc) => {
|
||||||
this.openDocumentsService.refreshDocument(doc.id)
|
this.openDocumentsService.refreshDocument(doc.id)
|
||||||
@@ -203,7 +198,16 @@ export class AppFrameComponent
|
|||||||
) {
|
) {
|
||||||
this.tasksService.reload()
|
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
|
this.lastScrollY = window.scrollY
|
||||||
@@ -552,44 +556,6 @@ export class AppFrameComponent
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
private openReleaseNotes(
|
|
||||||
since: string | null,
|
|
||||||
until: string | null = null
|
|
||||||
): void {
|
|
||||||
const modal = this.modalService.open(ReleaseNotesDialogComponent, {
|
|
||||||
size: 'lg',
|
|
||||||
scrollable: true,
|
|
||||||
})
|
|
||||||
modal.componentInstance.load(since, until)
|
|
||||||
modal.componentInstance.updateCheckingChosen.subscribe((enable: boolean) =>
|
|
||||||
this.setUpdateChecking(enable)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
showReleaseNotes() {
|
|
||||||
const since = this.settingsService.unseenReleasesSince()
|
|
||||||
this.openReleaseNotes(since)
|
|
||||||
if (since) {
|
|
||||||
this.dismissReleaseNotes()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Mark the running version's release notes seen, hiding "New" */
|
|
||||||
dismissReleaseNotes() {
|
|
||||||
this.settingsService
|
|
||||||
.markReleasesSeen()
|
|
||||||
.pipe(first())
|
|
||||||
.subscribe({ error: () => {} })
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Notes for releases newer than the running version, not yet installed */
|
|
||||||
showAvailableReleaseNotes() {
|
|
||||||
this.openReleaseNotes(
|
|
||||||
this.settingsService.get(SETTINGS_KEYS.VERSION),
|
|
||||||
this.appRemoteVersion()?.version
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
setUpdateChecking(enable: boolean) {
|
setUpdateChecking(enable: boolean) {
|
||||||
this.settingsService.set(SETTINGS_KEYS.UPDATE_CHECKING_ENABLED, enable)
|
this.settingsService.set(SETTINGS_KEYS.UPDATE_CHECKING_ENABLED, enable)
|
||||||
this.settingsService
|
this.settingsService
|
||||||
|
|||||||
@@ -188,62 +188,6 @@ describe('ChatComponent', () => {
|
|||||||
expect(component.loading()).toBe(false)
|
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', () => {
|
it('should show a slow response message while waiting', () => {
|
||||||
component.input.set('Hello')
|
component.input.set('Hello')
|
||||||
component.sendMessage()
|
component.sendMessage()
|
||||||
|
|||||||
@@ -21,9 +21,6 @@ import {
|
|||||||
import { pngxPopperOptions } from 'src/app/utils/popper-options'
|
import { pngxPopperOptions } from 'src/app/utils/popper-options'
|
||||||
|
|
||||||
const SLOW_RESPONSE_DELAY_MS = 8000
|
const SLOW_RESPONSE_DELAY_MS = 8000
|
||||||
const TYPEWRITER_MIN_DURATION_MS = 750
|
|
||||||
const TYPEWRITER_MAX_DURATION_MS = 3000
|
|
||||||
const TYPEWRITER_INTERVAL_MS = 16
|
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'pngx-chat',
|
selector: 'pngx-chat',
|
||||||
@@ -76,7 +73,6 @@ export class ChatComponent implements OnInit {
|
|||||||
private typewriterBuffer: string[] = []
|
private typewriterBuffer: string[] = []
|
||||||
private typewriterActive = false
|
private typewriterActive = false
|
||||||
private typewriterTimeout: ReturnType<typeof setTimeout>
|
private typewriterTimeout: ReturnType<typeof setTimeout>
|
||||||
private typewriterDeadline = 0
|
|
||||||
private streamSubscription: Subscription
|
private streamSubscription: Subscription
|
||||||
private streamingMessage: ChatMessage
|
private streamingMessage: ChatMessage
|
||||||
private streamFinished = false
|
private streamFinished = false
|
||||||
@@ -138,7 +134,7 @@ export class ChatComponent implements OnInit {
|
|||||||
if (nextResponse.content.length < lastVisibleContent.length) {
|
if (nextResponse.content.length < lastVisibleContent.length) {
|
||||||
this.resetTypewriter(assistantMessage, nextResponse.content)
|
this.resetTypewriter(assistantMessage, nextResponse.content)
|
||||||
lastVisibleContent = nextResponse.content
|
lastVisibleContent = nextResponse.content
|
||||||
} else if (nextResponse.content.length > lastVisibleContent.length) {
|
} else {
|
||||||
const visibleDelta = nextResponse.content.substring(
|
const visibleDelta = nextResponse.content.substring(
|
||||||
lastVisibleContent.length
|
lastVisibleContent.length
|
||||||
)
|
)
|
||||||
@@ -218,12 +214,6 @@ export class ChatComponent implements OnInit {
|
|||||||
if (!chunk) return
|
if (!chunk) return
|
||||||
|
|
||||||
this.typewriterBuffer.push(...chunk.split(''))
|
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) {
|
if (!this.typewriterActive) {
|
||||||
this.typewriterActive = true
|
this.typewriterActive = true
|
||||||
@@ -232,29 +222,19 @@ export class ChatComponent implements OnInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
playTypewriter(message: ChatMessage): void {
|
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) {
|
if (this.typewriterBuffer.length === 0) {
|
||||||
this.typewriterActive = false
|
this.typewriterActive = false
|
||||||
if (this.streamFinished) this.finishStreaming(message)
|
if (this.streamFinished) this.finishStreaming(message)
|
||||||
} else {
|
return
|
||||||
this.typewriterTimeout = setTimeout(
|
|
||||||
() => this.playTypewriter(message),
|
|
||||||
TYPEWRITER_INTERVAL_MS
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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 {
|
private notifyMessagesChanged(): void {
|
||||||
|
|||||||
@@ -16,7 +16,6 @@ import basket from 'bootstrap-icons/icons/basket.svg'
|
|||||||
import bell from 'bootstrap-icons/icons/bell.svg'
|
import bell from 'bootstrap-icons/icons/bell.svg'
|
||||||
import bodyText from 'bootstrap-icons/icons/body-text.svg'
|
import bodyText from 'bootstrap-icons/icons/body-text.svg'
|
||||||
import bookmark from 'bootstrap-icons/icons/bookmark.svg'
|
import bookmark from 'bootstrap-icons/icons/bookmark.svg'
|
||||||
import boundingBoxCircles from 'bootstrap-icons/icons/bounding-box-circles.svg'
|
|
||||||
import boxArrowInRight from 'bootstrap-icons/icons/box-arrow-in-right.svg'
|
import boxArrowInRight from 'bootstrap-icons/icons/box-arrow-in-right.svg'
|
||||||
import boxArrowUpRight from 'bootstrap-icons/icons/box-arrow-up-right.svg'
|
import boxArrowUpRight from 'bootstrap-icons/icons/box-arrow-up-right.svg'
|
||||||
import boxArrowUp from 'bootstrap-icons/icons/box-arrow-up.svg'
|
import boxArrowUp from 'bootstrap-icons/icons/box-arrow-up.svg'
|
||||||
@@ -68,7 +67,6 @@ import exclamationCircleFill from 'bootstrap-icons/icons/exclamation-circle-fill
|
|||||||
import exclamationTriangleFill from 'bootstrap-icons/icons/exclamation-triangle-fill.svg'
|
import exclamationTriangleFill from 'bootstrap-icons/icons/exclamation-triangle-fill.svg'
|
||||||
import exclamationTriangle from 'bootstrap-icons/icons/exclamation-triangle.svg'
|
import exclamationTriangle from 'bootstrap-icons/icons/exclamation-triangle.svg'
|
||||||
import eye from 'bootstrap-icons/icons/eye.svg'
|
import eye from 'bootstrap-icons/icons/eye.svg'
|
||||||
import eyeSlash from 'bootstrap-icons/icons/eye-slash.svg'
|
|
||||||
import fileEarmarkArrowUp from 'bootstrap-icons/icons/file-earmark-arrow-up.svg'
|
import fileEarmarkArrowUp from 'bootstrap-icons/icons/file-earmark-arrow-up.svg'
|
||||||
import fileEarmarkCheck from 'bootstrap-icons/icons/file-earmark-check.svg'
|
import fileEarmarkCheck from 'bootstrap-icons/icons/file-earmark-check.svg'
|
||||||
import fileEarmarkDiff from 'bootstrap-icons/icons/file-earmark-diff.svg'
|
import fileEarmarkDiff from 'bootstrap-icons/icons/file-earmark-diff.svg'
|
||||||
@@ -79,7 +77,6 @@ import fileEarmarkMinus from 'bootstrap-icons/icons/file-earmark-minus.svg'
|
|||||||
import fileEarmarkPerson from 'bootstrap-icons/icons/file-earmark-person.svg'
|
import fileEarmarkPerson from 'bootstrap-icons/icons/file-earmark-person.svg'
|
||||||
import fileEarmarkPlus from 'bootstrap-icons/icons/file-earmark-plus.svg'
|
import fileEarmarkPlus from 'bootstrap-icons/icons/file-earmark-plus.svg'
|
||||||
import fileEarmarkRichtext from 'bootstrap-icons/icons/file-earmark-richtext.svg'
|
import fileEarmarkRichtext from 'bootstrap-icons/icons/file-earmark-richtext.svg'
|
||||||
import fileEarmarkRuled from 'bootstrap-icons/icons/file-earmark-ruled.svg'
|
|
||||||
import fileEarmarkSpreadsheet from 'bootstrap-icons/icons/file-earmark-spreadsheet.svg'
|
import fileEarmarkSpreadsheet from 'bootstrap-icons/icons/file-earmark-spreadsheet.svg'
|
||||||
import fileEarmark from 'bootstrap-icons/icons/file-earmark.svg'
|
import fileEarmark from 'bootstrap-icons/icons/file-earmark.svg'
|
||||||
import fileText from 'bootstrap-icons/icons/file-text.svg'
|
import fileText from 'bootstrap-icons/icons/file-text.svg'
|
||||||
@@ -90,7 +87,6 @@ import folderFill from 'bootstrap-icons/icons/folder-fill.svg'
|
|||||||
import folder from 'bootstrap-icons/icons/folder.svg'
|
import folder from 'bootstrap-icons/icons/folder.svg'
|
||||||
import funnel from 'bootstrap-icons/icons/funnel.svg'
|
import funnel from 'bootstrap-icons/icons/funnel.svg'
|
||||||
import gear from 'bootstrap-icons/icons/gear.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 globe2 from 'bootstrap-icons/icons/globe2.svg'
|
||||||
import google from 'bootstrap-icons/icons/google.svg'
|
import google from 'bootstrap-icons/icons/google.svg'
|
||||||
import grid from 'bootstrap-icons/icons/grid.svg'
|
import grid from 'bootstrap-icons/icons/grid.svg'
|
||||||
@@ -135,7 +131,6 @@ import search from 'bootstrap-icons/icons/search.svg'
|
|||||||
import send from 'bootstrap-icons/icons/send.svg'
|
import send from 'bootstrap-icons/icons/send.svg'
|
||||||
import shop from 'bootstrap-icons/icons/shop.svg'
|
import shop from 'bootstrap-icons/icons/shop.svg'
|
||||||
import slashCircle from 'bootstrap-icons/icons/slash-circle.svg'
|
import slashCircle from 'bootstrap-icons/icons/slash-circle.svg'
|
||||||
import sliders2 from 'bootstrap-icons/icons/sliders2.svg'
|
|
||||||
import sliders2Vertical from 'bootstrap-icons/icons/sliders2-vertical.svg'
|
import sliders2Vertical from 'bootstrap-icons/icons/sliders2-vertical.svg'
|
||||||
import sortAlphaDown from 'bootstrap-icons/icons/sort-alpha-down.svg'
|
import sortAlphaDown from 'bootstrap-icons/icons/sort-alpha-down.svg'
|
||||||
import sortAlphaUpAlt from 'bootstrap-icons/icons/sort-alpha-up-alt.svg'
|
import sortAlphaUpAlt from 'bootstrap-icons/icons/sort-alpha-up-alt.svg'
|
||||||
@@ -184,7 +179,6 @@ export const icons: Record<string, string> = {
|
|||||||
braces,
|
braces,
|
||||||
bodyText,
|
bodyText,
|
||||||
bookmark,
|
bookmark,
|
||||||
boundingBoxCircles,
|
|
||||||
boxArrowInRight,
|
boxArrowInRight,
|
||||||
boxArrowUp,
|
boxArrowUp,
|
||||||
boxArrowUpRight,
|
boxArrowUpRight,
|
||||||
@@ -235,7 +229,6 @@ export const icons: Record<string, string> = {
|
|||||||
exclamationTriangle,
|
exclamationTriangle,
|
||||||
exclamationTriangleFill,
|
exclamationTriangleFill,
|
||||||
eye,
|
eye,
|
||||||
eyeSlash,
|
|
||||||
fileEarmark,
|
fileEarmark,
|
||||||
fileEarmarkArrowUp,
|
fileEarmarkArrowUp,
|
||||||
fileEarmarkCheck,
|
fileEarmarkCheck,
|
||||||
@@ -247,7 +240,6 @@ export const icons: Record<string, string> = {
|
|||||||
fileEarmarkPerson,
|
fileEarmarkPerson,
|
||||||
fileEarmarkPlus,
|
fileEarmarkPlus,
|
||||||
fileEarmarkRichtext,
|
fileEarmarkRichtext,
|
||||||
fileEarmarkRuled,
|
|
||||||
fileEarmarkSpreadsheet,
|
fileEarmarkSpreadsheet,
|
||||||
files,
|
files,
|
||||||
fileText,
|
fileText,
|
||||||
@@ -257,7 +249,6 @@ export const icons: Record<string, string> = {
|
|||||||
folderFill,
|
folderFill,
|
||||||
funnel,
|
funnel,
|
||||||
gear,
|
gear,
|
||||||
github,
|
|
||||||
globe2,
|
globe2,
|
||||||
google,
|
google,
|
||||||
grid,
|
grid,
|
||||||
@@ -301,7 +292,6 @@ export const icons: Record<string, string> = {
|
|||||||
search,
|
search,
|
||||||
send,
|
send,
|
||||||
slashCircle,
|
slashCircle,
|
||||||
sliders2,
|
|
||||||
shop,
|
shop,
|
||||||
sliders2Vertical,
|
sliders2Vertical,
|
||||||
sortAlphaDown,
|
sortAlphaDown,
|
||||||
|
|||||||
+2
-7
@@ -18,13 +18,8 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="form-check">
|
<div class="form-check">
|
||||||
<input class="form-check-input" type="checkbox" id="runWorkflowForce" [(ngModel)]="force" />
|
<input class="form-check-input" type="checkbox" id="runWorkflowForce" [(ngModel)]="force" />
|
||||||
@if (singleDocument) {
|
<label class="form-check-label" for="runWorkflowForce" i18n>Run on all selected documents</label>
|
||||||
<label class="form-check-label" for="runWorkflowForce" i18n>Run on this document regardless of trigger filters</label>
|
<div class="form-text" i18n>Ignore the workflow's trigger filters and run on every selected document.</div>
|
||||||
<div class="form-text" i18n>Ignore the workflow's trigger filters for this document.</div>
|
|
||||||
} @else {
|
|
||||||
<label class="form-check-label" for="runWorkflowForce" i18n>Run on all selected documents</label>
|
|
||||||
<div class="form-text" i18n>Ignore the workflow's trigger filters and run on every selected document.</div>
|
|
||||||
}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="modal-footer">
|
<div class="modal-footer">
|
||||||
|
|||||||
-21
@@ -39,25 +39,4 @@ describe('RunWorkflowConfirmDialogComponent', () => {
|
|||||||
expect(options).toHaveLength(2)
|
expect(options).toHaveLength(2)
|
||||||
expect(options[1].textContent).toContain('Manual workflow')
|
expect(options[1].textContent).toContain('Manual workflow')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should describe the checkbox for a selection or a single document', async () => {
|
|
||||||
const checkbox = fixture.nativeElement.querySelector('#runWorkflowForce')
|
|
||||||
expect(checkbox.checked).toBe(false)
|
|
||||||
expect(fixture.nativeElement.textContent).toContain(
|
|
||||||
'Run on all selected documents'
|
|
||||||
)
|
|
||||||
|
|
||||||
component.singleDocument = true
|
|
||||||
component.force = true
|
|
||||||
fixture.detectChanges()
|
|
||||||
await fixture.whenStable()
|
|
||||||
fixture.detectChanges()
|
|
||||||
expect(checkbox.checked).toBe(true)
|
|
||||||
expect(fixture.nativeElement.textContent).toContain(
|
|
||||||
'Run on this document regardless of trigger filters'
|
|
||||||
)
|
|
||||||
expect(fixture.nativeElement.textContent).not.toContain(
|
|
||||||
'Run on all selected documents'
|
|
||||||
)
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
-2
@@ -13,8 +13,6 @@ export class RunWorkflowConfirmDialogComponent extends ConfirmDialogComponent {
|
|||||||
|
|
||||||
public workflowId: number = null
|
public workflowId: number = null
|
||||||
|
|
||||||
public singleDocument: boolean = false
|
|
||||||
|
|
||||||
// i.e. ignore the workflow's trigger filters
|
// i.e. ignore the workflow's trigger filters
|
||||||
public force: boolean = false
|
public force: boolean = false
|
||||||
|
|
||||||
|
|||||||
-30
@@ -1,30 +0,0 @@
|
|||||||
<div class="modal-header">
|
|
||||||
<h4 class="modal-title" id="modal-basic-title">{{title}}</h4>
|
|
||||||
<button type="button" class="btn-close" aria-label="Close" (click)="cancel()">
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<div class="modal-body">
|
|
||||||
@if (messageBold) {
|
|
||||||
<p class="text-break"><b>{{messageBold}}</b></p>
|
|
||||||
}
|
|
||||||
@if (message) {
|
|
||||||
<p class="text-break" [innerHTML]="message"></p>
|
|
||||||
}
|
|
||||||
<pngx-input-select
|
|
||||||
[items]="templates()"
|
|
||||||
[(ngModel)]="template"
|
|
||||||
[allowNull]="true"
|
|
||||||
title="OCR template"
|
|
||||||
i18n-title
|
|
||||||
placeholder="All matching templates"
|
|
||||||
i18n-placeholder
|
|
||||||
></pngx-input-select>
|
|
||||||
</div>
|
|
||||||
<div class="modal-footer">
|
|
||||||
<button type="button" class="btn" [class]="cancelBtnClass" (click)="cancel()" [disabled]="!buttonsEnabled()">
|
|
||||||
<span class="d-inline-block" style="padding-bottom: 1px;">{{cancelBtnCaption}}</span>
|
|
||||||
</button>
|
|
||||||
<button type="button" class="btn" [class]="btnClass" (click)="confirm()" [disabled]="!confirmButtonEnabled || !buttonsEnabled()">
|
|
||||||
{{btnCaption}}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
-52
@@ -1,52 +0,0 @@
|
|||||||
import { provideHttpClient, withInterceptorsFromDi } from '@angular/common/http'
|
|
||||||
import { provideHttpClientTesting } from '@angular/common/http/testing'
|
|
||||||
import { ComponentFixture, TestBed } from '@angular/core/testing'
|
|
||||||
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'
|
|
||||||
import { of } from 'rxjs'
|
|
||||||
import { MATCH_NONE } from 'src/app/data/matching-model'
|
|
||||||
import { OcrTemplate } from 'src/app/data/ocr-template'
|
|
||||||
import { OcrTemplateService } from 'src/app/services/rest/ocr-template.service'
|
|
||||||
import { ZoneOcrConfirmDialogComponent } from './zone-ocr-confirm-dialog.component'
|
|
||||||
|
|
||||||
const templates: OcrTemplate[] = [
|
|
||||||
{
|
|
||||||
id: 1,
|
|
||||||
name: 'Invoices',
|
|
||||||
match: '',
|
|
||||||
matching_algorithm: MATCH_NONE,
|
|
||||||
sample_document: null,
|
|
||||||
source_width: 0,
|
|
||||||
source_height: 0,
|
|
||||||
enabled: true,
|
|
||||||
zones: [],
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
describe('ZoneOcrConfirmDialogComponent', () => {
|
|
||||||
let component: ZoneOcrConfirmDialogComponent
|
|
||||||
let fixture: ComponentFixture<ZoneOcrConfirmDialogComponent>
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
TestBed.configureTestingModule({
|
|
||||||
providers: [
|
|
||||||
NgbActiveModal,
|
|
||||||
provideHttpClient(withInterceptorsFromDi()),
|
|
||||||
provideHttpClientTesting(),
|
|
||||||
],
|
|
||||||
imports: [ZoneOcrConfirmDialogComponent],
|
|
||||||
})
|
|
||||||
jest
|
|
||||||
.spyOn(TestBed.inject(OcrTemplateService), 'listAll')
|
|
||||||
.mockReturnValue(of({ count: 1, all: [1], results: templates }))
|
|
||||||
|
|
||||||
fixture = TestBed.createComponent(ZoneOcrConfirmDialogComponent)
|
|
||||||
component = fixture.componentInstance
|
|
||||||
fixture.detectChanges()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should offer templates and default to all matching templates', () => {
|
|
||||||
expect(component.templates()).toEqual(templates)
|
|
||||||
expect(component.template).toBeNull()
|
|
||||||
expect(fixture.nativeElement.textContent).toContain('OCR template')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
-31
@@ -1,31 +0,0 @@
|
|||||||
import { Component, OnInit, inject, signal } from '@angular/core'
|
|
||||||
import { FormsModule } from '@angular/forms'
|
|
||||||
import { takeUntil } from 'rxjs'
|
|
||||||
import { OcrTemplate } from 'src/app/data/ocr-template'
|
|
||||||
import { OcrTemplateService } from 'src/app/services/rest/ocr-template.service'
|
|
||||||
import { SelectComponent } from '../../input/select/select.component'
|
|
||||||
import { ConfirmDialogComponent } from '../confirm-dialog.component'
|
|
||||||
|
|
||||||
@Component({
|
|
||||||
selector: 'pngx-zone-ocr-confirm-dialog',
|
|
||||||
templateUrl: './zone-ocr-confirm-dialog.component.html',
|
|
||||||
imports: [FormsModule, SelectComponent],
|
|
||||||
})
|
|
||||||
export class ZoneOcrConfirmDialogComponent
|
|
||||||
extends ConfirmDialogComponent
|
|
||||||
implements OnInit
|
|
||||||
{
|
|
||||||
private readonly ocrTemplateService = inject(OcrTemplateService)
|
|
||||||
|
|
||||||
public readonly templates = signal<OcrTemplate[]>([])
|
|
||||||
|
|
||||||
/** The template to run, or null for every template that matches. */
|
|
||||||
template: number | null = null
|
|
||||||
|
|
||||||
ngOnInit() {
|
|
||||||
this.ocrTemplateService
|
|
||||||
.listAll()
|
|
||||||
.pipe(takeUntil(this.unsubscribeNotifier))
|
|
||||||
.subscribe((r) => this.templates.set(r.results))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+11
@@ -4,6 +4,7 @@ import { ComponentFixture, TestBed } from '@angular/core/testing'
|
|||||||
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
|
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
|
||||||
import { By } from '@angular/platform-browser'
|
import { By } from '@angular/platform-browser'
|
||||||
import {
|
import {
|
||||||
|
NgbDropdown,
|
||||||
NgbDropdownModule,
|
NgbDropdownModule,
|
||||||
NgbModal,
|
NgbModal,
|
||||||
NgbModalModule,
|
NgbModalModule,
|
||||||
@@ -250,4 +251,14 @@ describe('CustomFieldsDropdownComponent', () => {
|
|||||||
expect(createFieldSpy).not.toHaveBeenCalled()
|
expect(createFieldSpy).not.toHaveBeenCalled()
|
||||||
expect(addFieldSpy).not.toHaveBeenCalled()
|
expect(addFieldSpy).not.toHaveBeenCalled()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('should close the dropdown after selecting a filtered field', () => {
|
||||||
|
const dropdown = fixture.debugElement
|
||||||
|
.query(By.directive(NgbDropdown))
|
||||||
|
.injector.get(NgbDropdown)
|
||||||
|
dropdown.open()
|
||||||
|
component.filterText = 'Field 1'
|
||||||
|
component.listFilterEnter()
|
||||||
|
expect(dropdown.isOpen()).toBe(false)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
+7
-1
@@ -11,7 +11,11 @@ import {
|
|||||||
signal,
|
signal,
|
||||||
} from '@angular/core'
|
} from '@angular/core'
|
||||||
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
|
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
|
||||||
import { NgbDropdownModule, NgbModal } from '@ng-bootstrap/ng-bootstrap'
|
import {
|
||||||
|
NgbDropdown,
|
||||||
|
NgbDropdownModule,
|
||||||
|
NgbModal,
|
||||||
|
} from '@ng-bootstrap/ng-bootstrap'
|
||||||
import { first, takeUntil } from 'rxjs'
|
import { first, takeUntil } from 'rxjs'
|
||||||
import { BootstrapIconComponent } from 'src/app/components/common/bootstrap-icon/bootstrap-icon.component'
|
import { BootstrapIconComponent } from 'src/app/components/common/bootstrap-icon/bootstrap-icon.component'
|
||||||
import { CustomField, DATA_TYPE_LABELS } from 'src/app/data/custom-field'
|
import { CustomField, DATA_TYPE_LABELS } from 'src/app/data/custom-field'
|
||||||
@@ -63,6 +67,7 @@ export class CustomFieldsDropdownComponent extends LoadingComponentWithPermissio
|
|||||||
created: EventEmitter<CustomField> = new EventEmitter()
|
created: EventEmitter<CustomField> = new EventEmitter()
|
||||||
|
|
||||||
@ViewChild('listFilterTextInput') listFilterTextInput: ElementRef
|
@ViewChild('listFilterTextInput') listFilterTextInput: ElementRef
|
||||||
|
@ViewChild('fieldDropdown') fieldDropdown: NgbDropdown
|
||||||
@ViewChildren('button') buttons: QueryList<ElementRef>
|
@ViewChildren('button') buttons: QueryList<ElementRef>
|
||||||
|
|
||||||
private customFields: CustomField[] = []
|
private customFields: CustomField[] = []
|
||||||
@@ -120,6 +125,7 @@ export class CustomFieldsDropdownComponent extends LoadingComponentWithPermissio
|
|||||||
|
|
||||||
addField(field: CustomField) {
|
addField(field: CustomField) {
|
||||||
this.added.emit(field)
|
this.added.emit(field)
|
||||||
|
this.fieldDropdown.close()
|
||||||
this.updateUnusedFields()
|
this.updateUnusedFields()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
-27
@@ -1290,33 +1290,6 @@ describe('WorkflowEditDialogComponent', () => {
|
|||||||
])
|
])
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should preserve commas in passwords when saving', () => {
|
|
||||||
component.object = {
|
|
||||||
name: 'Workflow with comma in password',
|
|
||||||
id: 1,
|
|
||||||
order: 1,
|
|
||||||
enabled: true,
|
|
||||||
triggers: [],
|
|
||||||
actions: [
|
|
||||||
{
|
|
||||||
id: 1,
|
|
||||||
type: WorkflowActionType.PasswordRemoval,
|
|
||||||
passwords: ['first,part', 'second'],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
}
|
|
||||||
component.ngOnInit()
|
|
||||||
|
|
||||||
const formActions = component.objectForm.get('actions') as FormArray
|
|
||||||
expect(formActions.value[0].passwords).toBe('first,part\nsecond')
|
|
||||||
component.save()
|
|
||||||
|
|
||||||
expect(component.objectForm.get('actions').value[0].passwords).toEqual([
|
|
||||||
'first,part',
|
|
||||||
'second',
|
|
||||||
])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should parse passwords again when retrying a failed save', () => {
|
it('should parse passwords again when retrying a failed save', () => {
|
||||||
component.object = {
|
component.object = {
|
||||||
name: 'Workflow with blank Passwords',
|
name: 'Workflow with blank Passwords',
|
||||||
|
|||||||
+1
-1
@@ -1332,7 +1332,7 @@ export class WorkflowEditDialogComponent
|
|||||||
}
|
}
|
||||||
|
|
||||||
private parsePasswords(value: string | string[] = ''): string[] {
|
private parsePasswords(value: string | string[] = ''): string[] {
|
||||||
return (Array.isArray(value) ? value : value.split('\n'))
|
return (Array.isArray(value) ? value : value.split(/[\n,]+/))
|
||||||
.map((entry) => entry.trim())
|
.map((entry) => entry.trim())
|
||||||
.filter((entry) => entry.length > 0)
|
.filter((entry) => entry.length > 0)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +0,0 @@
|
|||||||
<span class="badge text-bg-secondary d-inline-flex align-items-center gap-1" title="Tags you don't have access to" i18n-title>
|
|
||||||
<pngx-bs-icon name="eye-slash" width=".8em" height=".8em"></pngx-bs-icon>
|
|
||||||
<ng-container i18n>{{count()}} hidden</ng-container>
|
|
||||||
</span>
|
|
||||||
-19
@@ -1,19 +0,0 @@
|
|||||||
import { ComponentFixture, TestBed } from '@angular/core/testing'
|
|
||||||
import { HiddenTagsBadgeComponent } from './hidden-tags-badge.component'
|
|
||||||
|
|
||||||
describe('HiddenTagsBadgeComponent', () => {
|
|
||||||
let fixture: ComponentFixture<HiddenTagsBadgeComponent>
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
TestBed.configureTestingModule({
|
|
||||||
imports: [HiddenTagsBadgeComponent],
|
|
||||||
})
|
|
||||||
fixture = TestBed.createComponent(HiddenTagsBadgeComponent)
|
|
||||||
fixture.componentRef.setInput('count', 3)
|
|
||||||
fixture.detectChanges()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should show the hidden tag count', () => {
|
|
||||||
expect(fixture.nativeElement.textContent).toContain('3 hidden')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
import { ChangeDetectionStrategy, Component, input } from '@angular/core'
|
|
||||||
import { BootstrapIconComponent } from '../bootstrap-icon/bootstrap-icon.component'
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A badge indicating the number of hidden tags.
|
|
||||||
*/
|
|
||||||
@Component({
|
|
||||||
selector: 'pngx-hidden-tags-badge',
|
|
||||||
templateUrl: './hidden-tags-badge.component.html',
|
|
||||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
|
||||||
imports: [BootstrapIconComponent],
|
|
||||||
})
|
|
||||||
export class HiddenTagsBadgeComponent {
|
|
||||||
readonly count = input.required<number>()
|
|
||||||
}
|
|
||||||
@@ -40,7 +40,7 @@
|
|||||||
(change)="onChange(selectedDocumentIDs)">
|
(change)="onChange(selectedDocumentIDs)">
|
||||||
<ng-template ng-label-tmp let-document="item">
|
<ng-template ng-label-tmp let-document="item">
|
||||||
<div class="d-flex align-items-center">
|
<div class="d-flex align-items-center">
|
||||||
@if (!disabled && multiple) {
|
@if (!disabled) {
|
||||||
<button class="btn p-0 lh-1" (click)="unselect(document)" (mousedown)="$event.stopImmediatePropagation()" type="button" title="Remove link" i18n-title><pngx-bs-icon name="x"></pngx-bs-icon></button>
|
<button class="btn p-0 lh-1" (click)="unselect(document)" (mousedown)="$event.stopImmediatePropagation()" type="button" title="Remove link" i18n-title><pngx-bs-icon name="x"></pngx-bs-icon></button>
|
||||||
}
|
}
|
||||||
@if (document.title) {
|
@if (document.title) {
|
||||||
|
|||||||
@@ -81,9 +81,6 @@ export class DocumentLinkComponent
|
|||||||
@Input()
|
@Input()
|
||||||
placeholder: string = $localize`Search for documents`
|
placeholder: string = $localize`Search for documents`
|
||||||
|
|
||||||
@Input()
|
|
||||||
multiple: boolean = true
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Parent for ng-select dropdown, needed to prevent close on click.
|
* Parent for ng-select dropdown, needed to prevent close on click.
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -1,90 +0,0 @@
|
|||||||
import { provideHttpClient } from '@angular/common/http'
|
|
||||||
import { provideHttpClientTesting } from '@angular/common/http/testing'
|
|
||||||
import { Component } from '@angular/core'
|
|
||||||
import { ComponentFixture, TestBed } from '@angular/core/testing'
|
|
||||||
import { FormControl, ReactiveFormsModule } from '@angular/forms'
|
|
||||||
import { NumberComponent } from './number/number.component'
|
|
||||||
import { TextComponent } from './text/text.component'
|
|
||||||
import { TextAreaComponent } from './textarea/textarea.component'
|
|
||||||
import { UrlComponent } from './url/url.component'
|
|
||||||
|
|
||||||
@Component({
|
|
||||||
imports: [
|
|
||||||
ReactiveFormsModule,
|
|
||||||
TextComponent,
|
|
||||||
NumberComponent,
|
|
||||||
TextAreaComponent,
|
|
||||||
UrlComponent,
|
|
||||||
],
|
|
||||||
template: `
|
|
||||||
<pngx-input-text [formControl]="control" />
|
|
||||||
<pngx-input-number [formControl]="control" [showAdd]="false" />
|
|
||||||
<pngx-input-textarea [formControl]="control" />
|
|
||||||
<pngx-input-url [formControl]="control" />
|
|
||||||
`,
|
|
||||||
})
|
|
||||||
class InputEventsHostComponent {
|
|
||||||
control = new FormControl<string | number | null>(null)
|
|
||||||
}
|
|
||||||
|
|
||||||
describe.each([
|
|
||||||
['text', 'pngx-input-text input', 'Edited text', 'Edited text'],
|
|
||||||
['number', 'pngx-input-number input', '42', 42],
|
|
||||||
['textarea', 'pngx-input-textarea textarea', 'Edited\ntext', 'Edited\ntext'],
|
|
||||||
['url', 'pngx-input-url input', 'https://example.com', 'https://example.com'],
|
|
||||||
])(
|
|
||||||
'%s input events',
|
|
||||||
(_type, selector: string, text: string, value: string | number) => {
|
|
||||||
let fixture: ComponentFixture<InputEventsHostComponent>
|
|
||||||
let control: FormControl<string | number | null>
|
|
||||||
let input: HTMLInputElement | HTMLTextAreaElement
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
TestBed.configureTestingModule({
|
|
||||||
imports: [InputEventsHostComponent],
|
|
||||||
providers: [provideHttpClient(), provideHttpClientTesting()],
|
|
||||||
})
|
|
||||||
fixture = TestBed.createComponent(InputEventsHostComponent)
|
|
||||||
control = fixture.componentInstance.control
|
|
||||||
})
|
|
||||||
|
|
||||||
async function render() {
|
|
||||||
fixture.detectChanges()
|
|
||||||
await fixture.whenStable()
|
|
||||||
input = fixture.nativeElement.querySelector(selector)
|
|
||||||
}
|
|
||||||
|
|
||||||
it('updates the form while typing and marks it touched only on blur', async () => {
|
|
||||||
await render()
|
|
||||||
const changed = jest.fn()
|
|
||||||
control.valueChanges.subscribe(changed)
|
|
||||||
input.value = text
|
|
||||||
input.dispatchEvent(new Event('input'))
|
|
||||||
expect(control.value).toBe(value)
|
|
||||||
expect(control.dirty).toBe(true)
|
|
||||||
expect(control.touched).toBe(false)
|
|
||||||
|
|
||||||
input.dispatchEvent(new Event('change'))
|
|
||||||
input.dispatchEvent(new Event('blur'))
|
|
||||||
expect(control.touched).toBe(true)
|
|
||||||
expect(changed).toHaveBeenCalledTimes(1)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('honors an explicit updateOn blur strategy', async () => {
|
|
||||||
control = new FormControl<string | number | null>(null, {
|
|
||||||
updateOn: 'blur',
|
|
||||||
})
|
|
||||||
fixture.componentInstance.control = control
|
|
||||||
await render()
|
|
||||||
input.value = text
|
|
||||||
input.dispatchEvent(new Event('input'))
|
|
||||||
expect(control.value).toBeNull()
|
|
||||||
expect(control.pristine).toBe(true)
|
|
||||||
|
|
||||||
input.dispatchEvent(new Event('blur'))
|
|
||||||
expect(control.value).toBe(value)
|
|
||||||
expect(control.dirty).toBe(true)
|
|
||||||
expect(control.touched).toBe(true)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
)
|
|
||||||
@@ -12,7 +12,7 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="position-relative" [class.col-md-9]="horizontal">
|
<div class="position-relative" [class.col-md-9]="horizontal">
|
||||||
<div class="input-group" [class.is-invalid]="error">
|
<div class="input-group" [class.is-invalid]="error">
|
||||||
<input #inputField type="number" class="form-control" [step]="step" [id]="inputId" [(ngModel)]="value" [ngModelOptions]="{standalone: true}" (ngModelChange)="onChange($event)" (blur)="onTouched()" [class.is-invalid]="error" [disabled]="disabled">
|
<input #inputField type="number" class="form-control" [step]="step" [id]="inputId" [(ngModel)]="value" [ngModelOptions]="{standalone: true}" (change)="onChange(value)" [class.is-invalid]="error" [disabled]="disabled">
|
||||||
@if (showAdd) {
|
@if (showAdd) {
|
||||||
<button class="btn btn-outline-secondary" type="button" id="button-addon1" (click)="nextAsn()" [disabled]="disabled">+1</button>
|
<button class="btn btn-outline-secondary" type="button" id="button-addon1" (click)="nextAsn()" [disabled]="disabled">+1</button>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
}
|
}
|
||||||
<div class="position-relative" [class.col-md-9]="horizontal">
|
<div class="position-relative" [class.col-md-9]="horizontal">
|
||||||
<div class="input-group flex-nowrap">
|
<div class="input-group flex-nowrap">
|
||||||
<ng-select #tagSelect name="tags" [items]="tags" bindLabel="name" bindValue="id" [ngModel]="value" (ngModelChange)="onModelChange($event)" [ngModelOptions]="{standalone: true}"
|
<ng-select #tagSelect name="tags" [items]="tags" bindLabel="name" bindValue="id" [(ngModel)]="value" [ngModelOptions]="{standalone: true}"
|
||||||
[disabled]="disabled"
|
[disabled]="disabled"
|
||||||
[multiple]="multiple"
|
[multiple]="multiple"
|
||||||
[closeOnSelect]="false"
|
[closeOnSelect]="false"
|
||||||
@@ -17,30 +17,16 @@
|
|||||||
[searchFn]="searchFn"
|
[searchFn]="searchFn"
|
||||||
addTagText="Add tag"
|
addTagText="Add tag"
|
||||||
i18n-addTagText
|
i18n-addTagText
|
||||||
[keyDownFn]="onKeyDown"
|
|
||||||
(add)="onAdd($event)"
|
(add)="onAdd($event)"
|
||||||
(change)="onChange(value)">
|
(change)="onChange(value)">
|
||||||
|
|
||||||
<ng-template ng-label-tmp let-item="item">
|
<ng-template ng-label-tmp let-item="item">
|
||||||
@if (isImplied(item.id)) {
|
<button class="tag-wrap btn p-0 d-flex align-items-center" (click)="removeTag(item.id)" (mousedown)="$event.stopImmediatePropagation()" type="button" title="Remove tag" i18n-title>
|
||||||
<span class="implied-tag"></span>
|
<pngx-bs-icon name="x" style="margin-inline-end: 1px;"></pngx-bs-icon>
|
||||||
} @else if (isHidden(item.id)) {
|
@if (item.id && tags) {
|
||||||
@if (item.id === hiddenTagIds[0]) {
|
<pngx-tag style="background-color: none;" [tag]="getTag(item.id)"></pngx-tag>
|
||||||
<button class="tag-wrap hidden-tags btn p-0 d-flex align-items-center mw-100" (click)="removeHiddenTags()" (mousedown)="$event.stopImmediatePropagation()" type="button" title="Remove tags you don't have access to" i18n-title>
|
|
||||||
<pngx-bs-icon name="x" style="margin-inline-end: 1px;"></pngx-bs-icon>
|
|
||||||
<pngx-hidden-tags-badge class="d-flex" [count]="hiddenTagIds.length"></pngx-hidden-tags-badge>
|
|
||||||
</button>
|
|
||||||
} @else {
|
|
||||||
<span class="implied-tag"></span>
|
|
||||||
}
|
}
|
||||||
} @else {
|
</button>
|
||||||
<button class="tag-wrap btn p-0 d-flex align-items-center mw-100" (click)="removeBadge(item.id)" (mousedown)="$event.stopImmediatePropagation()" type="button" title="Remove tag" i18n-title>
|
|
||||||
<pngx-bs-icon name="x" style="margin-inline-end: 1px;"></pngx-bs-icon>
|
|
||||||
@if (item.id && tags) {
|
|
||||||
<pngx-tag class="mw-100 overflow-hidden d-flex" [tag]="getTag(item.id)" [split]="preserveHierarchy" (click)="removeTag(item.id); $event.stopPropagation()" (parentClick)="removeTag($event)"></pngx-tag>
|
|
||||||
}
|
|
||||||
</button>
|
|
||||||
}
|
|
||||||
</ng-template>
|
</ng-template>
|
||||||
<ng-template ng-option-tmp let-item="item" let-index="index" let-search="searchTerm">
|
<ng-template ng-option-tmp let-item="item" let-index="index" let-search="searchTerm">
|
||||||
<div class="tag-option-row d-flex align-items-center" [class.w-auto]="!getTag(item.id)?.parent">
|
<div class="tag-option-row d-flex align-items-center" [class.w-auto]="!getTag(item.id)?.parent">
|
||||||
|
|||||||
@@ -7,30 +7,6 @@
|
|||||||
font-size: 1rem;
|
font-size: 1rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ancestors of another selected tag render inside that tag's badge
|
|
||||||
::ng-deep .paperless-input-tags .ng-value:has(> .implied-tag) {
|
|
||||||
display: none !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
// hidden tags bundle always sits after the visible tags
|
|
||||||
::ng-deep .paperless-input-tags .ng-value:has(> .hidden-tags) {
|
|
||||||
order: 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
::ng-deep .paperless-input-tags .ng-value-container .ng-input {
|
|
||||||
order: 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
// let a long (nowrap) split badge shrink to the field instead of widening it
|
|
||||||
ng-select,
|
|
||||||
::ng-deep .paperless-input-tags .ng-value-container {
|
|
||||||
min-width: 0 !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
::ng-deep .paperless-input-tags .ng-value {
|
|
||||||
max-width: 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.paperless-input-select.disabled {
|
.paperless-input-select.disabled {
|
||||||
.input-group {
|
.input-group {
|
||||||
cursor: not-allowed;
|
cursor: not-allowed;
|
||||||
|
|||||||
@@ -278,142 +278,4 @@ describe('TagsComponent', () => {
|
|||||||
component.tags = [lone]
|
component.tags = [lone]
|
||||||
expect(component.getParentChain(5)).toEqual([])
|
expect(component.getParentChain(5)).toEqual([])
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('hierarchy', () => {
|
|
||||||
const root: Tag = { id: 1, name: 'root' }
|
|
||||||
const mid: Tag = { id: 2, name: 'mid', parent: 1 }
|
|
||||||
const leaf: Tag = { id: 3, name: 'leaf', parent: 2 }
|
|
||||||
const other: Tag = { id: 4, name: 'other' }
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
component.tags = [root, mid, leaf, other]
|
|
||||||
component.value = [3, 2, 1, 4]
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should treat ancestors of another selected tag as implied', () => {
|
|
||||||
expect([1, 2, 3, 4].map((id) => component.isImplied(id))).toEqual([
|
|
||||||
true,
|
|
||||||
true,
|
|
||||||
false,
|
|
||||||
false,
|
|
||||||
])
|
|
||||||
component.preserveHierarchy = false
|
|
||||||
expect(component.isImplied(1)).toBe(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should remove a whole badge, keeping ancestors other tags still need', () => {
|
|
||||||
component.removeBadge(3)
|
|
||||||
expect(component.value).toEqual([4])
|
|
||||||
|
|
||||||
const sibling: Tag = { id: 5, name: 'sibling', parent: 1 }
|
|
||||||
component.tags = [root, mid, leaf, other, sibling]
|
|
||||||
component.value = [3, 2, 1, 5, 4]
|
|
||||||
component.removeBadge(3)
|
|
||||||
expect(component.value).toEqual([1, 5, 4])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should remove only the tag itself from a badge when hierarchy is not shown', () => {
|
|
||||||
component.preserveHierarchy = false
|
|
||||||
component.removeBadge(3)
|
|
||||||
expect(component.value).toEqual([2, 1, 4])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should remove the last visible tag on backspace, not a hidden ancestor', () => {
|
|
||||||
const backspace = new KeyboardEvent('keydown', { key: 'Backspace' })
|
|
||||||
expect(component.onKeyDown(backspace)).toBe(false)
|
|
||||||
expect(component.value).toEqual([3, 2, 1])
|
|
||||||
expect(component.onKeyDown(backspace)).toBe(false)
|
|
||||||
expect(component.value).toEqual([2, 1])
|
|
||||||
|
|
||||||
// nothing hidden: leave it to ng-select
|
|
||||||
component.value = [4]
|
|
||||||
expect(component.onKeyDown(backspace)).toBe(true)
|
|
||||||
expect(
|
|
||||||
component.onKeyDown(new KeyboardEvent('keydown', { key: 'a' }))
|
|
||||||
).toBe(true)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('hidden tags', () => {
|
|
||||||
// 98, 99 are not in the tags list i.e. the user cannot view them
|
|
||||||
beforeEach(() => {
|
|
||||||
component.tags = tags
|
|
||||||
component.value = [1, 98, 2, 99]
|
|
||||||
fixture.detectChanges()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should collapse hidden tags into a single badge', async () => {
|
|
||||||
await fixture.whenStable()
|
|
||||||
fixture.detectChanges()
|
|
||||||
expect(component.hiddenTagIds).toEqual([98, 99])
|
|
||||||
expect(component.isHidden(1)).toBe(false)
|
|
||||||
const badges = fixture.nativeElement.querySelectorAll('.ng-value')
|
|
||||||
const visible = Array.from(badges).filter(
|
|
||||||
(b: HTMLElement) => !b.querySelector('.implied-tag')
|
|
||||||
) as HTMLElement[]
|
|
||||||
expect(visible).toHaveLength(3)
|
|
||||||
expect(visible[1].textContent).toContain('2 hidden')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should only recompute hidden tags when the value or tags change', () => {
|
|
||||||
const first = component.hiddenTagIds
|
|
||||||
expect(component.hiddenTagIds).toBe(first)
|
|
||||||
component.value = [1, 99]
|
|
||||||
expect(component.hiddenTagIds).toEqual([99])
|
|
||||||
component.tags = [...tags, { id: 99, name: 'now visible' }]
|
|
||||||
expect(component.hiddenTagIds).toEqual([])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should not treat tags as hidden before tags load', () => {
|
|
||||||
;(component as any).tagsLoaded = false
|
|
||||||
expect(component.hiddenTagIds).toEqual([])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should not treat a hidden ancestor of a visible tag as hidden', () => {
|
|
||||||
component.tags = [{ id: 3, name: 'child', parent: 98 }]
|
|
||||||
component.value = [3, 98]
|
|
||||||
expect(component.hiddenTagIds).toEqual([])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should keep hidden tags when ng-select changes the selection', () => {
|
|
||||||
component.onModelChange([])
|
|
||||||
expect(component.value).toEqual([98, 99])
|
|
||||||
component.onModelChange([1, 10])
|
|
||||||
expect(component.value).toEqual([1, 10, 98, 99])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should skip hidden tags on backspace', () => {
|
|
||||||
const backspace = new KeyboardEvent('keydown', { key: 'Backspace' })
|
|
||||||
expect(component.onKeyDown(backspace)).toBe(false)
|
|
||||||
expect(component.value).toEqual([1, 98, 99])
|
|
||||||
expect(component.onKeyDown(backspace)).toBe(false)
|
|
||||||
expect(component.onKeyDown(backspace)).toBe(false)
|
|
||||||
expect(component.value).toEqual([98, 99])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should remove all hidden tags after confirmation', () => {
|
|
||||||
let propagated: number[]
|
|
||||||
component.registerOnChange((value: number[]) => (propagated = value))
|
|
||||||
let activeInstances: NgbModalRef[]
|
|
||||||
modalService.activeInstances.subscribe((v) => (activeInstances = v))
|
|
||||||
|
|
||||||
component.removeHiddenTags()
|
|
||||||
expect(modalService.hasOpenModals()).toBeTruthy()
|
|
||||||
expect(component.value).toEqual([1, 98, 2, 99])
|
|
||||||
|
|
||||||
activeInstances[0].componentInstance.confirmClicked.emit()
|
|
||||||
expect(component.value).toEqual([1, 2])
|
|
||||||
expect(propagated).toEqual([1, 2])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should not remove hidden tags when disabled or none exist', () => {
|
|
||||||
component.disabled = true
|
|
||||||
component.removeHiddenTags()
|
|
||||||
expect(modalService.hasOpenModals()).toBeFalsy()
|
|
||||||
component.disabled = false
|
|
||||||
component.value = [1]
|
|
||||||
component.removeHiddenTags()
|
|
||||||
expect(modalService.hasOpenModals()).toBeFalsy()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
@@ -21,13 +21,8 @@ import { NgSelectComponent, NgSelectModule } from '@ng-select/ng-select'
|
|||||||
import { first, firstValueFrom, tap } from 'rxjs'
|
import { first, firstValueFrom, tap } from 'rxjs'
|
||||||
import { BootstrapIconComponent } from 'src/app/components/common/bootstrap-icon/bootstrap-icon.component'
|
import { BootstrapIconComponent } from 'src/app/components/common/bootstrap-icon/bootstrap-icon.component'
|
||||||
import { Tag } from 'src/app/data/tag'
|
import { Tag } from 'src/app/data/tag'
|
||||||
import { SETTINGS_KEYS } from 'src/app/data/ui-settings'
|
|
||||||
import { TagService } from 'src/app/services/rest/tag.service'
|
import { TagService } from 'src/app/services/rest/tag.service'
|
||||||
import { SettingsService } from 'src/app/services/settings.service'
|
|
||||||
import { getTagAncestors, partitionTags } from 'src/app/utils/tag-display'
|
|
||||||
import { matchesSearchText } from 'src/app/utils/text-search'
|
import { matchesSearchText } from 'src/app/utils/text-search'
|
||||||
import { ConfirmDialogComponent } from '../../confirm-dialog/confirm-dialog.component'
|
|
||||||
import { HiddenTagsBadgeComponent } from '../../hidden-tags-badge/hidden-tags-badge.component'
|
|
||||||
import { EditDialogMode } from '../../edit-dialog/edit-dialog.component'
|
import { EditDialogMode } from '../../edit-dialog/edit-dialog.component'
|
||||||
import { TagEditDialogComponent } from '../../edit-dialog/tag-edit-dialog/tag-edit-dialog.component'
|
import { TagEditDialogComponent } from '../../edit-dialog/tag-edit-dialog/tag-edit-dialog.component'
|
||||||
import { TagComponent } from '../../tag/tag.component'
|
import { TagComponent } from '../../tag/tag.component'
|
||||||
@@ -50,13 +45,11 @@ import { TagComponent } from '../../tag/tag.component'
|
|||||||
ReactiveFormsModule,
|
ReactiveFormsModule,
|
||||||
RouterModule,
|
RouterModule,
|
||||||
BootstrapIconComponent,
|
BootstrapIconComponent,
|
||||||
HiddenTagsBadgeComponent,
|
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
export class TagsComponent implements OnInit, ControlValueAccessor {
|
export class TagsComponent implements OnInit, ControlValueAccessor {
|
||||||
private tagService = inject(TagService)
|
private tagService = inject(TagService)
|
||||||
private modalService = inject(NgbModal)
|
private modalService = inject(NgbModal)
|
||||||
private readonly settingsService = inject(SettingsService)
|
|
||||||
private readonly changeDetector = inject(ChangeDetectorRef)
|
private readonly changeDetector = inject(ChangeDetectorRef)
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
@@ -85,7 +78,6 @@ export class TagsComponent implements OnInit, ControlValueAccessor {
|
|||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
this.tagService.listAll().subscribe((result) => {
|
this.tagService.listAll().subscribe((result) => {
|
||||||
this.tags = result.results
|
this.tags = result.results
|
||||||
this.tagsLoaded = true
|
|
||||||
this.changeDetector.markForCheck()
|
this.changeDetector.markForCheck()
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -129,8 +121,6 @@ export class TagsComponent implements OnInit, ControlValueAccessor {
|
|||||||
|
|
||||||
tags: Tag[] = []
|
tags: Tag[] = []
|
||||||
|
|
||||||
private tagsLoaded = false
|
|
||||||
|
|
||||||
public createTagRef: (name) => void
|
public createTagRef: (name) => void
|
||||||
|
|
||||||
public searchFn = (term: string, tag: Tag): boolean =>
|
public searchFn = (term: string, tag: Tag): boolean =>
|
||||||
@@ -141,118 +131,6 @@ export class TagsComponent implements OnInit, ControlValueAccessor {
|
|||||||
term
|
term
|
||||||
)
|
)
|
||||||
|
|
||||||
/**
|
|
||||||
* Selected tags that are ancestors of another selected tag which are shown
|
|
||||||
* as segments of their descendant's badge.
|
|
||||||
*/
|
|
||||||
isImplied(id: number): boolean {
|
|
||||||
return !!this.value?.includes(id) && !this.display.shown.has(id)
|
|
||||||
}
|
|
||||||
|
|
||||||
private get showsHierarchy(): boolean {
|
|
||||||
return (
|
|
||||||
this.preserveHierarchy &&
|
|
||||||
!!this.settingsService.get(SETTINGS_KEYS.TAGS_SHOW_HIERARCHY)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
isHidden(id: number): boolean {
|
|
||||||
return this.display.hiddenSet.has(id)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Tags that are hidden from the current user.
|
|
||||||
*/
|
|
||||||
get hiddenTagIds(): number[] {
|
|
||||||
return this.display.hidden
|
|
||||||
}
|
|
||||||
|
|
||||||
private displayCache: {
|
|
||||||
value: number[]
|
|
||||||
tagsById: Map<number, Tag>
|
|
||||||
showsHierarchy: boolean
|
|
||||||
tagsLoaded: boolean
|
|
||||||
shown: Set<number>
|
|
||||||
hidden: number[]
|
|
||||||
hiddenSet: Set<number>
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Partition of the current value, recomputed only when the value, tags or
|
|
||||||
* hierarchy setting change.
|
|
||||||
*/
|
|
||||||
private get display() {
|
|
||||||
const tagsById = this.tagsById
|
|
||||||
const showsHierarchy = this.showsHierarchy
|
|
||||||
const cached = this.displayCache
|
|
||||||
if (
|
|
||||||
cached?.value === this.value &&
|
|
||||||
cached.tagsById === tagsById &&
|
|
||||||
cached.showsHierarchy === showsHierarchy &&
|
|
||||||
cached.tagsLoaded === this.tagsLoaded
|
|
||||||
) {
|
|
||||||
return cached
|
|
||||||
}
|
|
||||||
const { visible, hidden } = partitionTags(
|
|
||||||
this.value,
|
|
||||||
tagsById,
|
|
||||||
showsHierarchy
|
|
||||||
)
|
|
||||||
const hiddenIds = this.tagsLoaded ? hidden : []
|
|
||||||
this.displayCache = {
|
|
||||||
value: this.value,
|
|
||||||
tagsById,
|
|
||||||
showsHierarchy,
|
|
||||||
tagsLoaded: this.tagsLoaded,
|
|
||||||
shown: new Set([...visible, ...hidden]),
|
|
||||||
hidden: hiddenIds,
|
|
||||||
hiddenSet: new Set(hiddenIds),
|
|
||||||
}
|
|
||||||
return this.displayCache
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Remove the last visible tag (in case its actually a hidden ancestor or a
|
|
||||||
* tag the user cannot view)
|
|
||||||
*/
|
|
||||||
readonly onKeyDown = (event: KeyboardEvent): boolean => {
|
|
||||||
if (event.key !== 'Backspace' || this.select?.searchTerm) return true
|
|
||||||
const visible =
|
|
||||||
this.value?.filter((id) => !this.isImplied(id) && !this.isHidden(id)) ??
|
|
||||||
[]
|
|
||||||
if (visible.length === (this.value?.length ?? 0)) return true
|
|
||||||
if (visible.length) this.removeTag(visible.at(-1))
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Changes from ng-select itself (e.g. clear all) never drop hidden tags,
|
|
||||||
* those are only removed via their own badge.
|
|
||||||
*/
|
|
||||||
onModelChange(newValue: number[]) {
|
|
||||||
const kept = this.hiddenTagIds.filter((id) => !newValue?.includes(id))
|
|
||||||
this.value = [...(newValue ?? []), ...kept]
|
|
||||||
}
|
|
||||||
|
|
||||||
removeHiddenTags() {
|
|
||||||
if (this.disabled) return
|
|
||||||
const hidden = new Set(this.hiddenTagIds)
|
|
||||||
if (!hidden.size) return
|
|
||||||
const modal = this.modalService.open(ConfirmDialogComponent, {
|
|
||||||
backdrop: 'static',
|
|
||||||
})
|
|
||||||
modal.componentInstance.title = $localize`Remove hidden tags`
|
|
||||||
modal.componentInstance.messageBold = $localize`Remove ${hidden.size} tag(s) you don't have access to?`
|
|
||||||
modal.componentInstance.message = $localize`You will not be able to add them back.`
|
|
||||||
modal.componentInstance.btnClass = 'btn-danger'
|
|
||||||
modal.componentInstance.btnCaption = $localize`Remove`
|
|
||||||
modal.componentInstance.confirmClicked.pipe(first()).subscribe(() => {
|
|
||||||
modal.close()
|
|
||||||
this.value = this.value.filter((id) => !hidden.has(id))
|
|
||||||
this.onChange(this.value)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
getTag(id: number) {
|
getTag(id: number) {
|
||||||
if (this.tags) {
|
if (this.tags) {
|
||||||
return this.tags.find((tag) => tag.id == id)
|
return this.tags.find((tag) => tag.id == id)
|
||||||
@@ -261,26 +139,6 @@ export class TagsComponent implements OnInit, ControlValueAccessor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Remove a whole badge i.e. the tag plus any ancestors that no other selected
|
|
||||||
* tag still needs.
|
|
||||||
*/
|
|
||||||
removeBadge(tagID: number) {
|
|
||||||
if (this.disabled) return
|
|
||||||
if (!this.showsHierarchy) return this.removeTag(tagID)
|
|
||||||
|
|
||||||
const ancestors = new Set(this.getParentChain(tagID).map((t) => t.id))
|
|
||||||
const needed = new Set(
|
|
||||||
this.value
|
|
||||||
.filter((id) => id !== tagID && !ancestors.has(id))
|
|
||||||
.flatMap((id) => this.getParentChain(id).map((t) => t.id))
|
|
||||||
)
|
|
||||||
this.value = this.value.filter(
|
|
||||||
(id) => id !== tagID && (!ancestors.has(id) || needed.has(id))
|
|
||||||
)
|
|
||||||
this.onChange(this.value)
|
|
||||||
}
|
|
||||||
|
|
||||||
removeTag(tagID: number) {
|
removeTag(tagID: number) {
|
||||||
if (this.disabled) return
|
if (this.disabled) return
|
||||||
|
|
||||||
@@ -377,17 +235,18 @@ export class TagsComponent implements OnInit, ControlValueAccessor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
getParentChain(id: number): Tag[] {
|
getParentChain(id: number): Tag[] {
|
||||||
return getTagAncestors(id, this.tagsById)
|
// Returns ancestors from root → immediate parent for a tag id
|
||||||
}
|
const chain: Tag[] = []
|
||||||
|
let current = this.getTag(id)
|
||||||
private tagsByIdSource: Tag[]
|
const guard = new Set<number>()
|
||||||
private tagsByIdCache: Map<number, Tag>
|
while (current?.parent) {
|
||||||
|
if (guard.has(current.parent)) break
|
||||||
private get tagsById(): Map<number, Tag> {
|
guard.add(current.parent)
|
||||||
if (this.tagsByIdSource !== this.tags) {
|
const parent = this.getTag(current.parent)
|
||||||
this.tagsByIdSource = this.tags
|
if (!parent) break
|
||||||
this.tagsByIdCache = new Map(this.tags?.map((t) => [t.id, t]))
|
chain.unshift(parent)
|
||||||
|
current = parent
|
||||||
}
|
}
|
||||||
return this.tagsByIdCache
|
return chain
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -11,7 +11,7 @@
|
|||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
<div class="position-relative" [class.col-md-9]="horizontal">
|
<div class="position-relative" [class.col-md-9]="horizontal">
|
||||||
<input #inputField type="text" class="form-control" [class.is-invalid]="error" [id]="inputId" [(ngModel)]="value" [ngModelOptions]="{standalone: true}" (ngModelChange)="onChange($event)" (blur)="onTouched()" [disabled]="disabled" [autocomplete]="autocomplete" [placeholder]="placeholder">
|
<input #inputField type="text" class="form-control" [class.is-invalid]="error" [id]="inputId" [(ngModel)]="value" [ngModelOptions]="{standalone: true}" (change)="onChange(value)" [disabled]="disabled" [autocomplete]="autocomplete" [placeholder]="placeholder">
|
||||||
@if (hint) {
|
@if (hint) {
|
||||||
<small class="form-text text-muted" [innerHTML]="hint"></small>
|
<small class="form-text text-muted" [innerHTML]="hint"></small>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,8 +18,7 @@
|
|||||||
[class.font-monospace]="monospace"
|
[class.font-monospace]="monospace"
|
||||||
[(ngModel)]="value"
|
[(ngModel)]="value"
|
||||||
[ngModelOptions]="{standalone: true}"
|
[ngModelOptions]="{standalone: true}"
|
||||||
(ngModelChange)="onChange($event)"
|
(change)="onChange(value)"
|
||||||
(blur)="onTouched()"
|
|
||||||
[disabled]="disabled"
|
[disabled]="disabled"
|
||||||
[placeholder]="placeholder"
|
[placeholder]="placeholder"
|
||||||
rows="4">
|
rows="4">
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
</div>
|
</div>
|
||||||
<div [class.col-md-9]="horizontal">
|
<div [class.col-md-9]="horizontal">
|
||||||
<div class="input-group" [class.is-invalid]="error">
|
<div class="input-group" [class.is-invalid]="error">
|
||||||
<input #inputField type="url" class="form-control" [class.is-invalid]="error" placeholder="https://" [id]="inputId" [(ngModel)]="value" [ngModelOptions]="{standalone: true}" (ngModelChange)="onChange($event)" (blur)="onTouched()" [disabled]="disabled">
|
<input #inputField type="url" class="form-control" [class.is-invalid]="error" placeholder="https://" [id]="inputId" [(ngModel)]="value" [ngModelOptions]="{standalone: true}" (change)="onChange(value)" [disabled]="disabled">
|
||||||
<a class="btn btn-outline-secondary rounded-end" title="Open link" i18n-title [href]="value" target="_blank">
|
<a class="btn btn-outline-secondary rounded-end" title="Open link" i18n-title [href]="value" target="_blank">
|
||||||
<pngx-bs-icon width="1.2em" height="1.2em" name="box-arrow-up-right"></pngx-bs-icon>
|
<pngx-bs-icon width="1.2em" height="1.2em" name="box-arrow-up-right"></pngx-bs-icon>
|
||||||
</a>
|
</a>
|
||||||
|
|||||||
-92
@@ -1,92 +0,0 @@
|
|||||||
<div class="modal-header">
|
|
||||||
<div>
|
|
||||||
@if (until()) {
|
|
||||||
<h4 class="modal-title" i18n>Paperless-ngx {{ until() }} is available</h4>
|
|
||||||
<p class="text-muted small mb-0" i18n>You are running {{ version }}</p>
|
|
||||||
} @else {
|
|
||||||
<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()) {
|
|
||||||
@if (!updateCheckingIsSet() && canChangeUpdateChecking) {
|
|
||||||
<p class="mb-2" i18n>Paperless-ngx can automatically check for updates and show release notes here, fetched from GitHub.</p>
|
|
||||||
<div class="btn-group btn-group-sm">
|
|
||||||
<button type="button" class="btn btn-outline-primary" (click)="setUpdateChecking(true)" i18n>Enable</button>
|
|
||||||
<button type="button" class="btn btn-outline-secondary" (click)="setUpdateChecking(false)" i18n>Disable</button>
|
|
||||||
</div>
|
|
||||||
} @else {
|
|
||||||
<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>
|
|
||||||
<div class="d-flex gap-3">
|
|
||||||
<button type="button" class="btn btn-outline-secondary" (click)="close()" i18n>Close</button>
|
|
||||||
@if (until()) {
|
|
||||||
<a class="btn btn-primary d-flex align-items-center" [href]="updatingDocsUrl" target="_blank" rel="noopener noreferrer">
|
|
||||||
<ng-container i18n>How to update</ng-container>
|
|
||||||
<pngx-bs-icon name="box-arrow-up-right" class="ms-2" width=".8rem"></pngx-bs-icon>
|
|
||||||
</a>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
</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>
|
|
||||||
-77
@@ -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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-210
@@ -1,210 +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 { PermissionsService } from 'src/app/services/permissions.service'
|
|
||||||
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, canChangeSettings = true) {
|
|
||||||
settingsService = TestBed.inject(SettingsService)
|
|
||||||
settingsService.set(SETTINGS_KEYS.VERSION, '3.5.1')
|
|
||||||
if (updateCheckingEnabled !== undefined) {
|
|
||||||
settingsService.set(
|
|
||||||
SETTINGS_KEYS.UPDATE_CHECKING_ENABLED,
|
|
||||||
updateCheckingEnabled
|
|
||||||
)
|
|
||||||
}
|
|
||||||
jest
|
|
||||||
.spyOn(TestBed.inject(PermissionsService), 'currentUserCan')
|
|
||||||
.mockReturnValue(canChangeSettings)
|
|
||||||
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('.modal-footer a.btn-primary')
|
|
||||||
).toBeNull()
|
|
||||||
expect(
|
|
||||||
fixture.nativeElement.querySelector('.release-notes-body details summary')
|
|
||||||
.textContent
|
|
||||||
).toEqual('1 change')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should load release notes for an available update', () => {
|
|
||||||
create(true)
|
|
||||||
component.load('3.5.1', '3.6.0')
|
|
||||||
httpTestingController
|
|
||||||
.expectOne(
|
|
||||||
`${environment.apiBaseUrl}release_notes/?since=3.5.1&until=3.6.0`
|
|
||||||
)
|
|
||||||
.flush({ version: '3.5.1', releases: [] })
|
|
||||||
fixture.detectChanges()
|
|
||||||
|
|
||||||
const text = fixture.nativeElement.textContent
|
|
||||||
expect(text).toContain('Paperless-ngx 3.6.0 is available')
|
|
||||||
expect(text).toContain('You are running 3.5.1')
|
|
||||||
expect(component.releaseUrl).toEqual(
|
|
||||||
'https://github.com/paperless-ngx/paperless-ngx/releases/tag/v3.6.0'
|
|
||||||
)
|
|
||||||
expect(
|
|
||||||
fixture.nativeElement
|
|
||||||
.querySelector('.modal-footer a.btn-primary')
|
|
||||||
.getAttribute('href')
|
|
||||||
).toEqual('https://docs.paperless-ngx.com/administration/#updating')
|
|
||||||
})
|
|
||||||
|
|
||||||
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 offer to enable update checking if never chosen', () => {
|
|
||||||
create()
|
|
||||||
const chosen = jest.fn()
|
|
||||||
component.updateCheckingChosen.subscribe(chosen)
|
|
||||||
component.load('3.4.2')
|
|
||||||
fixture.detectChanges()
|
|
||||||
|
|
||||||
const enable = Array.from(
|
|
||||||
fixture.nativeElement.querySelectorAll('.modal-body button')
|
|
||||||
).find((b: HTMLButtonElement) => b.textContent.trim() === 'Enable') as
|
|
||||||
HTMLButtonElement | undefined
|
|
||||||
expect(enable).toBeTruthy()
|
|
||||||
httpTestingController.expectNone(`${environment.apiBaseUrl}release_notes/`)
|
|
||||||
|
|
||||||
enable.click()
|
|
||||||
expect(chosen).toHaveBeenCalledWith(true)
|
|
||||||
httpTestingController
|
|
||||||
.expectOne(`${environment.apiBaseUrl}release_notes/?since=3.4.2`)
|
|
||||||
.flush({ version: '3.5.1', releases: [] })
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should show the disabled message after choosing disable', () => {
|
|
||||||
create()
|
|
||||||
const chosen = jest.fn()
|
|
||||||
component.updateCheckingChosen.subscribe(chosen)
|
|
||||||
component.load(null)
|
|
||||||
component.setUpdateChecking(false)
|
|
||||||
fixture.detectChanges()
|
|
||||||
|
|
||||||
expect(chosen).toHaveBeenCalledWith(false)
|
|
||||||
httpTestingController.expectNone(`${environment.apiBaseUrl}release_notes/`)
|
|
||||||
expect(fixture.nativeElement.textContent).toContain(
|
|
||||||
'when update checking is enabled'
|
|
||||||
)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should not offer to enable update checking without permission', () => {
|
|
||||||
create(undefined, false)
|
|
||||||
component.load(null)
|
|
||||||
fixture.detectChanges()
|
|
||||||
|
|
||||||
expect(fixture.nativeElement.textContent).not.toContain('Enable')
|
|
||||||
expect(fixture.nativeElement.textContent).toContain(
|
|
||||||
'when update checking is enabled'
|
|
||||||
)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should support close', () => {
|
|
||||||
create(false)
|
|
||||||
const closeSpy = jest.spyOn(component.activeModal, 'close')
|
|
||||||
component.close()
|
|
||||||
expect(closeSpy).toHaveBeenCalled()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
-131
@@ -1,131 +0,0 @@
|
|||||||
import { DecimalPipe, NgTemplateOutlet } from '@angular/common'
|
|
||||||
import { Component, inject, output, 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 {
|
|
||||||
PermissionAction,
|
|
||||||
PermissionsService,
|
|
||||||
PermissionType,
|
|
||||||
} from 'src/app/services/permissions.service'
|
|
||||||
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`
|
|
||||||
const UPDATING_DOCS_URL =
|
|
||||||
'https://docs.paperless-ngx.com/administration/#updating'
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 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)
|
|
||||||
private readonly permissionsService = inject(PermissionsService)
|
|
||||||
|
|
||||||
readonly since = signal<string | null>(null)
|
|
||||||
readonly until = 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 = signal<boolean>(
|
|
||||||
this.settingsService.get(SETTINGS_KEYS.UPDATE_CHECKING_ENABLED)
|
|
||||||
)
|
|
||||||
readonly updateCheckingIsSet = signal(
|
|
||||||
this.settingsService.updateCheckingIsSet
|
|
||||||
)
|
|
||||||
readonly canChangeUpdateChecking = this.permissionsService.currentUserCan(
|
|
||||||
PermissionAction.Change,
|
|
||||||
PermissionType.UISettings
|
|
||||||
)
|
|
||||||
|
|
||||||
readonly updateCheckingChosen = output<boolean>()
|
|
||||||
|
|
||||||
readonly repoUrl = REPO_URL
|
|
||||||
readonly releasesUrl = RELEASES_URL
|
|
||||||
readonly discussionsUrl = DISCUSSIONS_URL
|
|
||||||
readonly updatingDocsUrl = UPDATING_DOCS_URL
|
|
||||||
|
|
||||||
get releaseUrl(): string {
|
|
||||||
const version = this.until() ?? this.version
|
|
||||||
return version ? `${RELEASES_URL}/tag/v${version}` : RELEASES_URL
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Load notes for releases after `since` up to `until` (default: the
|
|
||||||
* running version), or just the `until` version's notes if `since` is null.
|
|
||||||
*/
|
|
||||||
load(since: string | null, until: string | null = null): void {
|
|
||||||
this.since.set(since)
|
|
||||||
this.until.set(until)
|
|
||||||
if (!this.updateCheckingEnabled()) return
|
|
||||||
this.loading.set(true)
|
|
||||||
this.remoteVersionService
|
|
||||||
.getReleaseNotes(since ?? undefined, until ?? 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)
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
setUpdateChecking(enable: boolean): void {
|
|
||||||
this.updateCheckingIsSet.set(true)
|
|
||||||
this.updateCheckingEnabled.set(enable)
|
|
||||||
this.updateCheckingChosen.emit(enable)
|
|
||||||
if (enable) this.load(this.since(), this.until())
|
|
||||||
}
|
|
||||||
|
|
||||||
close(): void {
|
|
||||||
this.activeModal.close()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,18 +1,13 @@
|
|||||||
@if (tag()) {
|
@if (tag()) {
|
||||||
@if (ancestorSegments.length) {
|
@if (showParents() && tag().parent) {
|
||||||
<span #pill class="split-pill d-inline-flex mw-100" [title]="path()" (mouseleave)="setFocus(pill, null)">
|
<pngx-tag [tagID]="tag().parent" [clickable]="clickable()" [linkTitle]="linkTitle()"></pngx-tag>
|
||||||
@for (ancestor of ancestorSegments; track ancestor.id; let first = $first) {
|
>
|
||||||
<span #segment class="badge split-parent" [class.rounded-end-0]="first" [class.rounded-0]="!first" [style.background]="ancestor.color" [style.color]="ancestor.text_color" (mouseenter)="setFocus(pill, segment)" (click)="onParentClick($event, ancestor.id)">{{ancestor.name}}</span>
|
}
|
||||||
}
|
@if (!clickable()) {
|
||||||
<span #leaf class="badge rounded-start-0 split-child" [style.background]="tag().color" [style.color]="tag().text_color" (mouseenter)="setFocus(pill, leaf)">{{tag().name}}</span>
|
<span class="badge" [style.background]="tag().color" [style.color]="tag().text_color">{{tag().name}}</span>
|
||||||
</span>
|
}
|
||||||
} @else {
|
@if (clickable()) {
|
||||||
@if (!clickable()) {
|
<a [title]="linkTitle()" class="badge" [style.background]="tag().color" [style.color]="tag().text_color">{{tag().name}}</a>
|
||||||
<span class="badge" [style.background]="tag().color" [style.color]="tag().text_color">{{tag().name}}</span>
|
|
||||||
}
|
|
||||||
@if (clickable()) {
|
|
||||||
<a [title]="linkTitle()" class="badge" [style.background]="tag().color" [style.color]="tag().text_color">{{tag().name}}</a>
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} @else if (loading) {
|
} @else if (loading) {
|
||||||
<span class="placeholder-glow">
|
<span class="placeholder-glow">
|
||||||
|
|||||||
@@ -11,46 +11,3 @@ a, span {
|
|||||||
opacity: .5;
|
opacity: .5;
|
||||||
font-style: italic;
|
font-style: italic;
|
||||||
}
|
}
|
||||||
|
|
||||||
.split-parent,
|
|
||||||
.split-child {
|
|
||||||
overflow: hidden;
|
|
||||||
white-space: nowrap;
|
|
||||||
transition: color .2s ease;
|
|
||||||
}
|
|
||||||
|
|
||||||
.split-parent {
|
|
||||||
min-width: 1.5em;
|
|
||||||
max-width: 10em;
|
|
||||||
padding-inline: .4em;
|
|
||||||
text-overflow: clip;
|
|
||||||
|
|
||||||
&:nth-last-child(2) { flex-shrink: 1e12; }
|
|
||||||
&:nth-last-child(3) { flex-shrink: 1e18; }
|
|
||||||
&:nth-last-child(4) { flex-shrink: 1e24; }
|
|
||||||
&:nth-last-child(5) { flex-shrink: 1e30; }
|
|
||||||
|
|
||||||
&.collapsed {
|
|
||||||
color: transparent !important;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.split-child {
|
|
||||||
flex-shrink: 1e6;
|
|
||||||
min-width: 2em;
|
|
||||||
max-width: 20em; // nowrap, so very long names would otherwise widen e.g. table columns
|
|
||||||
text-overflow: ellipsis;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Hovered segment gets priority, other parents can shrink to a sliver
|
|
||||||
.split-pill {
|
|
||||||
> .split-parent.focused,
|
|
||||||
> .split-child.focused {
|
|
||||||
flex-shrink: 1;
|
|
||||||
text-overflow: ellipsis;
|
|
||||||
}
|
|
||||||
|
|
||||||
&:has(> .focused) > .split-parent:not(.focused) {
|
|
||||||
min-width: 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -6,7 +6,6 @@ import { of } from 'rxjs'
|
|||||||
import { Tag } from 'src/app/data/tag'
|
import { Tag } from 'src/app/data/tag'
|
||||||
import { PermissionsService } from 'src/app/services/permissions.service'
|
import { PermissionsService } from 'src/app/services/permissions.service'
|
||||||
import { TagService } from 'src/app/services/rest/tag.service'
|
import { TagService } from 'src/app/services/rest/tag.service'
|
||||||
import { SettingsService } from 'src/app/services/settings.service'
|
|
||||||
import { TagComponent } from './tag.component'
|
import { TagComponent } from './tag.component'
|
||||||
|
|
||||||
const tag: Tag = {
|
const tag: Tag = {
|
||||||
@@ -70,88 +69,4 @@ describe('TagComponent', () => {
|
|||||||
expect(getCachedSpy).toHaveBeenCalledWith(1)
|
expect(getCachedSpy).toHaveBeenCalledWith(1)
|
||||||
expect(component.tag()).toEqual(tag)
|
expect(component.tag()).toEqual(tag)
|
||||||
})
|
})
|
||||||
describe('split badge', () => {
|
|
||||||
const root: Tag = { id: 1, name: 'Root', color: '#000000' }
|
|
||||||
const mid: Tag = { id: 2, name: 'Mid', color: '#111111', parent: 1 }
|
|
||||||
const leaf: Tag = { id: 3, name: 'Leaf', color: '#222222', parent: 2 }
|
|
||||||
|
|
||||||
const segments = (): HTMLElement[] =>
|
|
||||||
fixture.debugElement
|
|
||||||
.queryAll(By.css('.split-pill > .badge'))
|
|
||||||
.map((d) => d.nativeElement)
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
jest.spyOn(permissionsService, 'currentUserCan').mockReturnValue(true)
|
|
||||||
jest.spyOn(tagService, 'getCached').mockReturnValue(of(leaf))
|
|
||||||
jest
|
|
||||||
.spyOn(tagService, 'listAll')
|
|
||||||
.mockReturnValue(
|
|
||||||
of({ count: 3, all: [1, 2, 3], results: [root, mid, leaf] })
|
|
||||||
)
|
|
||||||
fixture.componentRef.setInput('tagID', 3)
|
|
||||||
fixture.componentRef.setInput('split', true)
|
|
||||||
fixture.detectChanges()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should render ancestors as segments with the full path as title', () => {
|
|
||||||
expect(segments().map((s) => s.textContent.trim())).toEqual([
|
|
||||||
'Root',
|
|
||||||
'Mid',
|
|
||||||
'Leaf',
|
|
||||||
])
|
|
||||||
expect(
|
|
||||||
fixture.debugElement.query(By.css('.split-pill')).nativeElement.title
|
|
||||||
).toEqual('Root › Mid › Leaf')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should render a plain badge when the setting is off', () => {
|
|
||||||
jest.spyOn(TestBed.inject(SettingsService), 'get').mockReturnValue(false)
|
|
||||||
fixture.componentRef.setInput('split', false)
|
|
||||||
fixture.detectChanges()
|
|
||||||
fixture.componentRef.setInput('split', true)
|
|
||||||
fixture.detectChanges()
|
|
||||||
expect(fixture.debugElement.query(By.css('.split-pill'))).toBeNull()
|
|
||||||
expect(component.ancestorSegments).toEqual([])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should emit the ancestor id when an ancestor segment is clicked', () => {
|
|
||||||
const emitSpy = jest.spyOn(component.parentClick, 'emit')
|
|
||||||
const event = new MouseEvent('click', { bubbles: true })
|
|
||||||
const stopSpy = jest.spyOn(event, 'stopImmediatePropagation')
|
|
||||||
segments()[1].dispatchEvent(event)
|
|
||||||
expect(emitSpy).toHaveBeenCalledWith(2)
|
|
||||||
expect(stopSpy).toHaveBeenCalled()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should focus the hovered segment and animate width changes', () => {
|
|
||||||
const [rootSeg, midSeg, leafSeg] = segments()
|
|
||||||
const pill = rootSeg.parentElement
|
|
||||||
// before / after widths per segment, as measured by setFocus
|
|
||||||
const widths = new Map<HTMLElement, number[]>([
|
|
||||||
[rootSeg, [20, 4]],
|
|
||||||
[midSeg, [20, 60]],
|
|
||||||
[leafSeg, [40, 40]],
|
|
||||||
])
|
|
||||||
const animate = jest.fn()
|
|
||||||
for (const [seg, [before, after]] of widths) {
|
|
||||||
seg.getAnimations = jest.fn(() => [])
|
|
||||||
seg.animate = animate
|
|
||||||
jest
|
|
||||||
.spyOn(seg, 'getBoundingClientRect')
|
|
||||||
.mockReturnValueOnce({ width: before } as DOMRect)
|
|
||||||
.mockReturnValueOnce({ width: after } as DOMRect)
|
|
||||||
}
|
|
||||||
|
|
||||||
midSeg.dispatchEvent(new MouseEvent('mouseenter'))
|
|
||||||
expect(midSeg.classList).toContain('focused')
|
|
||||||
expect(rootSeg.classList).not.toContain('focused')
|
|
||||||
// only the segments whose width changed are animated
|
|
||||||
expect(animate).toHaveBeenCalledTimes(2)
|
|
||||||
|
|
||||||
pill.dispatchEvent(new MouseEvent('mouseleave'))
|
|
||||||
expect(segments().some((s) => s.classList.contains('focused'))).toBe(
|
|
||||||
false
|
|
||||||
)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
@@ -1,27 +1,11 @@
|
|||||||
import {
|
import { Component, effect, inject, input, model } from '@angular/core'
|
||||||
Component,
|
|
||||||
computed,
|
|
||||||
effect,
|
|
||||||
inject,
|
|
||||||
input,
|
|
||||||
model,
|
|
||||||
output,
|
|
||||||
signal,
|
|
||||||
} from '@angular/core'
|
|
||||||
import { Tag } from 'src/app/data/tag'
|
import { Tag } from 'src/app/data/tag'
|
||||||
import { SETTINGS_KEYS } from 'src/app/data/ui-settings'
|
|
||||||
import {
|
import {
|
||||||
PermissionAction,
|
PermissionAction,
|
||||||
PermissionsService,
|
PermissionsService,
|
||||||
PermissionType,
|
PermissionType,
|
||||||
} from 'src/app/services/permissions.service'
|
} from 'src/app/services/permissions.service'
|
||||||
import { TagService } from 'src/app/services/rest/tag.service'
|
import { TagService } from 'src/app/services/rest/tag.service'
|
||||||
import { SettingsService } from 'src/app/services/settings.service'
|
|
||||||
import { getTagAncestors } from 'src/app/utils/tag-display'
|
|
||||||
|
|
||||||
const FOCUS_ANIMATION_MS = 200
|
|
||||||
// matches the .split-parent min-width in tag.component.scss
|
|
||||||
const COLLAPSE_BELOW_EM = 1.5
|
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'pngx-tag',
|
selector: 'pngx-tag',
|
||||||
@@ -29,9 +13,8 @@ const COLLAPSE_BELOW_EM = 1.5
|
|||||||
styleUrls: ['./tag.component.scss'],
|
styleUrls: ['./tag.component.scss'],
|
||||||
})
|
})
|
||||||
export class TagComponent {
|
export class TagComponent {
|
||||||
private readonly permissionsService = inject(PermissionsService)
|
private permissionsService = inject(PermissionsService)
|
||||||
private readonly tagService = inject(TagService)
|
private tagService = inject(TagService)
|
||||||
private readonly settingsService = inject(SettingsService)
|
|
||||||
|
|
||||||
readonly tag = model<Tag>(null)
|
readonly tag = model<Tag>(null)
|
||||||
readonly tagID = input<number>(undefined)
|
readonly tagID = input<number>(undefined)
|
||||||
@@ -40,101 +23,27 @@ export class TagComponent {
|
|||||||
transform: (value: boolean | string) =>
|
transform: (value: boolean | string) =>
|
||||||
value === '' || value === true || value === 'true',
|
value === '' || value === true || value === 'true',
|
||||||
})
|
})
|
||||||
|
readonly showParents = input(false)
|
||||||
readonly split = input(false)
|
|
||||||
|
|
||||||
readonly parentClick = output<number>()
|
|
||||||
|
|
||||||
private readonly ancestors = signal<Tag[]>([])
|
|
||||||
|
|
||||||
public get ancestorSegments(): Tag[] {
|
|
||||||
return this.split() &&
|
|
||||||
this.settingsService.get(SETTINGS_KEYS.TAGS_SHOW_HIERARCHY)
|
|
||||||
? this.ancestors()
|
|
||||||
: []
|
|
||||||
}
|
|
||||||
|
|
||||||
public readonly path = computed(() =>
|
|
||||||
[...this.ancestors(), this.tag()]
|
|
||||||
.filter(Boolean)
|
|
||||||
.map((t) => t.name)
|
|
||||||
.join(' › ')
|
|
||||||
)
|
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
effect(() => {
|
effect(() => {
|
||||||
const tagID = this.tagID()
|
const tagID = this.tagID()
|
||||||
if (tagID && this.canViewTags) {
|
if (tagID) {
|
||||||
this.tagService.getCached(tagID).subscribe((tag) => {
|
if (
|
||||||
this.tag.set(tag)
|
this.permissionsService.currentUserCan(
|
||||||
})
|
PermissionAction.View,
|
||||||
}
|
PermissionType.Tag
|
||||||
})
|
|
||||||
|
|
||||||
// ancestors for split badges, from either tagID or a passed-in tag
|
|
||||||
effect(() => {
|
|
||||||
const id = this.tagID() || this.tag()?.id
|
|
||||||
if (!this.split() || !id || !this.canViewTags) {
|
|
||||||
this.ancestors.set([])
|
|
||||||
return
|
|
||||||
}
|
|
||||||
this.tagService.listAll().subscribe((tags) => {
|
|
||||||
this.ancestors.set(
|
|
||||||
getTagAncestors(
|
|
||||||
id,
|
|
||||||
new Map<number, Tag>(tags.results.map((t) => [t.id, t]))
|
|
||||||
)
|
)
|
||||||
)
|
) {
|
||||||
})
|
this.tagService.getCached(tagID).subscribe((tag) => {
|
||||||
|
this.tag.set(tag)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
private get canViewTags(): boolean {
|
|
||||||
return this.permissionsService.currentUserCan(
|
|
||||||
PermissionAction.View,
|
|
||||||
PermissionType.Tag
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
public get loading(): boolean {
|
public get loading(): boolean {
|
||||||
return this.tagService.loading
|
return this.tagService.loading
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Gives the hovered segment priority (.focused class, see scss)
|
|
||||||
* and animates each from old width to new
|
|
||||||
*/
|
|
||||||
setFocus(segment: HTMLElement, focused: HTMLElement | null) {
|
|
||||||
const segments = Array.from(segment.children) as HTMLElement[]
|
|
||||||
const before = segments.map((s) => s.getBoundingClientRect().width)
|
|
||||||
for (const segment of segments) {
|
|
||||||
segment.getAnimations().forEach((a) => a.cancel())
|
|
||||||
segment.classList.toggle('focused', segment === focused)
|
|
||||||
}
|
|
||||||
const after = segments.map((s) => s.getBoundingClientRect().width)
|
|
||||||
|
|
||||||
segments.forEach((segment, i) => {
|
|
||||||
const em = Number.parseFloat(getComputedStyle(segment).fontSize)
|
|
||||||
segment.classList.toggle(
|
|
||||||
'collapsed',
|
|
||||||
!!focused &&
|
|
||||||
segment.classList.contains('split-parent') &&
|
|
||||||
after[i] < COLLAPSE_BELOW_EM * em
|
|
||||||
)
|
|
||||||
if (Math.abs(after[i] - before[i]) < 0.5) return
|
|
||||||
segment.animate(
|
|
||||||
[
|
|
||||||
{ flex: `0 0 ${before[i]}px`, minWidth: 0 },
|
|
||||||
{ flex: `0 0 ${after[i]}px`, minWidth: 0 },
|
|
||||||
],
|
|
||||||
{ duration: FOCUS_ANIMATION_MS, easing: 'ease' }
|
|
||||||
)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
onParentClick(event: MouseEvent, id: number) {
|
|
||||||
event.preventDefault()
|
|
||||||
event.stopImmediatePropagation()
|
|
||||||
this.parentClick.emit(id)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -7,7 +7,6 @@
|
|||||||
background-color: var(--pngx-toast-bg);
|
background-color: var(--pngx-toast-bg);
|
||||||
color: var(--bs-body-color);
|
color: var(--bs-body-color);
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
transition: background-color .18s ease, border-color .18s ease;
|
|
||||||
|
|
||||||
&.toast-success {
|
&.toast-success {
|
||||||
--pngx-toast-accent: var(--pngx-toast-success);
|
--pngx-toast-accent: var(--pngx-toast-success);
|
||||||
@@ -24,13 +23,6 @@
|
|||||||
|
|
||||||
.toast-icon {
|
.toast-icon {
|
||||||
color: var(--pngx-toast-accent);
|
color: var(--pngx-toast-accent);
|
||||||
transition: color .18s ease;
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (prefers-reduced-motion: reduce) {
|
|
||||||
.toast, .toast-icon {
|
|
||||||
transition: none;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.toast-content {
|
.toast-content {
|
||||||
|
|||||||
@@ -65,36 +65,6 @@ describe('ToastComponent', () => {
|
|||||||
expect(component.delayRemaining()).toEqual(3000)
|
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', () => {
|
it('should hide the toast when the countdown ends', () => {
|
||||||
jest.useFakeTimers()
|
jest.useFakeTimers()
|
||||||
const toast = { content: 'Info', delay: 3000 }
|
const toast = { content: 'Info', delay: 3000 }
|
||||||
|
|||||||
@@ -5,10 +5,8 @@ import {
|
|||||||
DestroyRef,
|
DestroyRef,
|
||||||
EventEmitter,
|
EventEmitter,
|
||||||
Input,
|
Input,
|
||||||
OnChanges,
|
|
||||||
OnInit,
|
OnInit,
|
||||||
Output,
|
Output,
|
||||||
SimpleChanges,
|
|
||||||
ViewChild,
|
ViewChild,
|
||||||
inject,
|
inject,
|
||||||
signal,
|
signal,
|
||||||
@@ -36,10 +34,10 @@ import { Toast, ToastLevel } from 'src/app/services/toast.service'
|
|||||||
styleUrl: './toast.component.scss',
|
styleUrl: './toast.component.scss',
|
||||||
providers: [DatePipe, CustomDatePipe],
|
providers: [DatePipe, CustomDatePipe],
|
||||||
})
|
})
|
||||||
export class ToastComponent implements OnInit, OnChanges {
|
export class ToastComponent implements OnInit {
|
||||||
private readonly clipboard = inject(Clipboard)
|
private clipboard = inject(Clipboard)
|
||||||
private readonly customDatePipe = inject(CustomDatePipe)
|
private customDatePipe = inject(CustomDatePipe)
|
||||||
private readonly destroyRef = inject(DestroyRef)
|
private destroyRef = inject(DestroyRef)
|
||||||
readonly copied = signal(false)
|
readonly copied = signal(false)
|
||||||
readonly ToastLevel = ToastLevel
|
readonly ToastLevel = ToastLevel
|
||||||
readonly delayRemaining = signal<number>(null)
|
readonly delayRemaining = signal<number>(null)
|
||||||
@@ -71,12 +69,6 @@ export class ToastComponent implements OnInit, OnChanges {
|
|||||||
if (this.autohide) this.delayRemaining.set(this.toast.delay)
|
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 {
|
get relativeTimestamp(): string {
|
||||||
return this.customDatePipe.transform(this.toast.timestamp, 'relative')
|
return this.customDatePipe.transform(this.toast.timestamp, 'relative')
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -68,9 +68,9 @@ describe('ToastsComponent', () => {
|
|||||||
toasts.forEach((t) => toastSubject.next(t))
|
toasts.forEach((t) => toastSubject.next(t))
|
||||||
expect(component.toasts().map((t) => t.id)).toEqual(['3', '2', '1'])
|
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])
|
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', () => {
|
it('should remove a popup when it hides without closing it', () => {
|
||||||
|
|||||||
@@ -32,11 +32,10 @@ export class ToastsComponent {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
this.toasts.update((toasts) =>
|
this.toasts.update((toasts) =>
|
||||||
toasts.some((existing) => existing.id === toast.id)
|
[toast, ...toasts.filter((t) => t.id !== toast.id)].slice(
|
||||||
? toasts.map((existing) =>
|
0,
|
||||||
existing.id === toast.id ? toast : existing
|
MAX_VISIBLE_TOASTS
|
||||||
)
|
)
|
||||||
: [toast, ...toasts].slice(0, MAX_VISIBLE_TOASTS)
|
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-6
@@ -76,12 +76,8 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
@case (DisplayField.TAGS) {
|
@case (DisplayField.TAGS) {
|
||||||
@let tags = doc.tags | displayTags | async;
|
@for (tagID of doc.tags; track tagID) {
|
||||||
@for (tagID of tags?.visible; track tagID) {
|
<pngx-tag [tagID]="tagID" class="ms-1 fs-6" (click)="clickTag(tagID, $event)" [clickable]="true" linkTitle="Filter by tag" i18n-title></pngx-tag>
|
||||||
<pngx-tag [tagID]="tagID" [split]="true" class="ms-1 fs-6" (click)="clickTag(tagID, $event)" (parentClick)="clickTag($event)" [clickable]="true" linkTitle="Filter by tag" i18n-title></pngx-tag>
|
|
||||||
}
|
|
||||||
@if (tags?.hidden.length) {
|
|
||||||
<pngx-hidden-tags-badge [count]="tags.hidden.length" class="ms-1 fs-6"></pngx-hidden-tags-badge>
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@case (DisplayField.DOCUMENT_TYPE) {
|
@case (DisplayField.DOCUMENT_TYPE) {
|
||||||
|
|||||||
-4
@@ -1,4 +1,3 @@
|
|||||||
import { HiddenTagsBadgeComponent } from 'src/app/components/common/hidden-tags-badge/hidden-tags-badge.component'
|
|
||||||
import { AsyncPipe, NgClass, NgStyle } from '@angular/common'
|
import { AsyncPipe, NgClass, NgStyle } from '@angular/common'
|
||||||
import {
|
import {
|
||||||
Component,
|
Component,
|
||||||
@@ -39,7 +38,6 @@ import {
|
|||||||
} from 'src/app/data/filter-rule-type'
|
} from 'src/app/data/filter-rule-type'
|
||||||
import { SavedView } from 'src/app/data/saved-view'
|
import { SavedView } from 'src/app/data/saved-view'
|
||||||
import { IfPermissionsDirective } from 'src/app/directives/if-permissions.directive'
|
import { IfPermissionsDirective } from 'src/app/directives/if-permissions.directive'
|
||||||
import { DisplayTagsPipe } from 'src/app/pipes/display-tags.pipe'
|
|
||||||
import { CorrespondentNamePipe } from 'src/app/pipes/correspondent-name.pipe'
|
import { CorrespondentNamePipe } from 'src/app/pipes/correspondent-name.pipe'
|
||||||
import { CustomDatePipe } from 'src/app/pipes/custom-date.pipe'
|
import { CustomDatePipe } from 'src/app/pipes/custom-date.pipe'
|
||||||
import { DocumentTitlePipe } from 'src/app/pipes/document-title.pipe'
|
import { DocumentTitlePipe } from 'src/app/pipes/document-title.pipe'
|
||||||
@@ -77,8 +75,6 @@ import { WidgetFrameComponent } from '../widget-frame/widget-frame.component'
|
|||||||
DocumentTypeNamePipe,
|
DocumentTypeNamePipe,
|
||||||
StoragePathNamePipe,
|
StoragePathNamePipe,
|
||||||
AsyncPipe,
|
AsyncPipe,
|
||||||
DisplayTagsPipe,
|
|
||||||
HiddenTagsBadgeComponent,
|
|
||||||
DocumentTitlePipe,
|
DocumentTitlePipe,
|
||||||
CustomDatePipe,
|
CustomDatePipe,
|
||||||
NgClass,
|
NgClass,
|
||||||
|
|||||||
@@ -67,22 +67,6 @@
|
|||||||
<pngx-bs-icon name="pencil" class="me-2"></pngx-bs-icon><ng-container i18n>PDF Editor</ng-container>
|
<pngx-bs-icon name="pencil" class="me-2"></pngx-bs-icon><ng-container i18n>PDF Editor</ng-container>
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<div class="d-flex" *pngxIfPermissions="{ action: PermissionAction.View, type: PermissionType.OcrTemplate }">
|
|
||||||
<button ngbDropdownItem (click)="runZoneOcr()" [disabled]="!userCanEdit || networkActive()">
|
|
||||||
<pngx-bs-icon width="1em" height="1em" name="bounding-box-circles" class="me-2"></pngx-bs-icon><span i18n>Run Zone OCR</span>
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
ngbDropdownItem
|
|
||||||
class="w-auto flex-shrink-0 px-2"
|
|
||||||
(click)="runZoneOcrWithOptions()"
|
|
||||||
[disabled]="!userCanEdit || networkActive()"
|
|
||||||
title="Choose OCR template"
|
|
||||||
i18n-title
|
|
||||||
>
|
|
||||||
<pngx-bs-icon width="1em" height="1em" name="sliders2"></pngx-bs-icon>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
@if (userIsOwner && (requiresPassword || password)) {
|
@if (userIsOwner && (requiresPassword || password)) {
|
||||||
<button ngbDropdownItem (click)="removePassword()" [disabled]="!password">
|
<button ngbDropdownItem (click)="removePassword()" [disabled]="!password">
|
||||||
<pngx-bs-icon name="unlock" class="me-2"></pngx-bs-icon><ng-container i18n>Remove Password</ng-container>
|
<pngx-bs-icon name="unlock" class="me-2"></pngx-bs-icon><ng-container i18n>Remove Password</ng-container>
|
||||||
@@ -112,7 +96,7 @@
|
|||||||
<div class="row">
|
<div class="row">
|
||||||
<div class="col-md-6 col-xl-5 mb-4">
|
<div class="col-md-6 col-xl-5 mb-4">
|
||||||
|
|
||||||
<form [formGroup]='documentForm' (ngSubmit)="save()" [attr.inert]="zoneOcrRunning() ? '' : null" [attr.aria-busy]="zoneOcrRunning()">
|
<form [formGroup]='documentForm' (ngSubmit)="save()">
|
||||||
|
|
||||||
<div class="btn-toolbar mb-1 pb-3 gap-2 row-gap-2 border-bottom">
|
<div class="btn-toolbar mb-1 pb-3 gap-2 row-gap-2 border-bottom">
|
||||||
<div class="btn-group">
|
<div class="btn-group">
|
||||||
@@ -513,7 +497,7 @@
|
|||||||
(loadError)="onError($event)"
|
(loadError)="onError($event)"
|
||||||
(afterLoadComplete)="pdfPreviewLoaded($event)">
|
(afterLoadComplete)="pdfPreviewLoaded($event)">
|
||||||
</pngx-pdf-viewer>
|
</pngx-pdf-viewer>
|
||||||
<div class="preview-controls position-absolute bottom-0 start-50 translate-middle-x z-1 mb-5 d-flex gap-2 p-1 bg-body border rounded shadow">
|
<div class="preview-controls position-absolute bottom-0 start-50 translate-middle-x z-1 mb-3 d-flex gap-2 p-1 bg-body border rounded shadow">
|
||||||
@if (previewNumPages()) {
|
@if (previewNumPages()) {
|
||||||
<div class="input-group input-group-sm w-auto flex-nowrap">
|
<div class="input-group input-group-sm w-auto flex-nowrap">
|
||||||
<input class="form-control flex-grow-0 w-auto" type="number" min="1" [max]="previewNumPages()" [ngModelOptions]="{standalone: true}" [ngModel]="previewCurrentPage()" (ngModelChange)="previewCurrentPage.set($event)" aria-label="Page" i18n-aria-label />
|
<input class="form-control flex-grow-0 w-auto" type="number" min="1" [max]="previewNumPages()" [ngModelOptions]="{standalone: true}" [ngModel]="previewCurrentPage()" (ngModelChange)="previewCurrentPage.set($event)" aria-label="Page" i18n-aria-label />
|
||||||
|
|||||||
@@ -41,7 +41,6 @@ import {
|
|||||||
FILTER_STORAGE_PATH,
|
FILTER_STORAGE_PATH,
|
||||||
} from 'src/app/data/filter-rule-type'
|
} from 'src/app/data/filter-rule-type'
|
||||||
import { StoragePath } from 'src/app/data/storage-path'
|
import { StoragePath } from 'src/app/data/storage-path'
|
||||||
import { PaperlessTaskStatus } from 'src/app/data/paperless-task'
|
|
||||||
import { Tag } from 'src/app/data/tag'
|
import { Tag } from 'src/app/data/tag'
|
||||||
import { SETTINGS_KEYS, SuggestionSource } from 'src/app/data/ui-settings'
|
import { SETTINGS_KEYS, SuggestionSource } from 'src/app/data/ui-settings'
|
||||||
import { PermissionsGuard } from 'src/app/guards/permissions.guard'
|
import { PermissionsGuard } from 'src/app/guards/permissions.guard'
|
||||||
@@ -60,7 +59,6 @@ import { TagService } from 'src/app/services/rest/tag.service'
|
|||||||
import { UserService } from 'src/app/services/rest/user.service'
|
import { UserService } from 'src/app/services/rest/user.service'
|
||||||
import { SettingsService } from 'src/app/services/settings.service'
|
import { SettingsService } from 'src/app/services/settings.service'
|
||||||
import { ToastService } from 'src/app/services/toast.service'
|
import { ToastService } from 'src/app/services/toast.service'
|
||||||
import { TaskNotificationService } from 'src/app/services/task-notification.service'
|
|
||||||
import { TrashService } from 'src/app/services/trash.service'
|
import { TrashService } from 'src/app/services/trash.service'
|
||||||
import { WebsocketStatusService } from 'src/app/services/websocket-status.service'
|
import { WebsocketStatusService } from 'src/app/services/websocket-status.service'
|
||||||
import { environment } from 'src/environments/environment'
|
import { environment } from 'src/environments/environment'
|
||||||
@@ -392,12 +390,14 @@ describe('DocumentDetailComponent', () => {
|
|||||||
expect(component.documentForm.get('title').value).toEqual('Foo Bar')
|
expect(component.documentForm.get('title').value).toEqual('Foo Bar')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should update the title form value without waiting for debounce or blur', () => {
|
it('should update title before doc change if was not updated via debounce', () => {
|
||||||
jest.useFakeTimers()
|
jest.useFakeTimers()
|
||||||
initNormally()
|
initNormally()
|
||||||
const input = component.titleInput.inputField.nativeElement
|
component.titleInput.value = 'Foo Bar'
|
||||||
input.value = 'Foo Bar'
|
component.titleInput.inputField.nativeElement.dispatchEvent(
|
||||||
input.dispatchEvent(new Event('input'))
|
new Event('change')
|
||||||
|
)
|
||||||
|
jest.advanceTimersByTime(1000)
|
||||||
expect(component.documentForm.get('title').value).toEqual('Foo Bar')
|
expect(component.documentForm.get('title').value).toEqual('Foo Bar')
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -1013,85 +1013,48 @@ describe('DocumentDetailComponent', () => {
|
|||||||
])
|
])
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should queue reprocess, show the task link and close the modal', () => {
|
it('should support reprocess, confirm and close modal after started', () => {
|
||||||
jest.useFakeTimers()
|
|
||||||
initNormally()
|
initNormally()
|
||||||
const reprocessSpy = jest.spyOn(documentService, 'reprocessDocuments')
|
const reprocessSpy = jest.spyOn(documentService, 'reprocessDocuments')
|
||||||
reprocessSpy.mockReturnValue(of({ result: 'OK', task_id: 'reprocess-1' }))
|
reprocessSpy.mockReturnValue(of(true))
|
||||||
let openModal: NgbModalRef
|
let openModal: NgbModalRef
|
||||||
modalService.activeInstances.subscribe((modal) => (openModal = modal[0]))
|
modalService.activeInstances.subscribe((modal) => (openModal = modal[0]))
|
||||||
const modalSpy = jest.spyOn(modalService, 'open')
|
const modalSpy = jest.spyOn(modalService, 'open')
|
||||||
const toastSpy = jest.spyOn(toastService, 'show')
|
const toastSpy = jest.spyOn(toastService, 'showInfo')
|
||||||
component.reprocess()
|
component.reprocess()
|
||||||
const modalCloseSpy = jest.spyOn(openModal, 'close')
|
const modalCloseSpy = jest.spyOn(openModal, 'close')
|
||||||
openModal.componentInstance.confirmClicked.next()
|
openModal.componentInstance.confirmClicked.next()
|
||||||
expect(reprocessSpy).toHaveBeenCalledWith({ documents: [doc.id] }, false)
|
expect(reprocessSpy).toHaveBeenCalledWith({ documents: [doc.id] }, false)
|
||||||
expect(modalSpy).toHaveBeenCalled()
|
expect(modalSpy).toHaveBeenCalled()
|
||||||
expect(toastSpy).not.toHaveBeenCalled()
|
expect(toastSpy).toHaveBeenCalled()
|
||||||
expect(modalCloseSpy).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', () => {
|
it('should run a workflow on the document, confirm and close modal', () => {
|
||||||
jest.useFakeTimers()
|
|
||||||
initNormally()
|
initNormally()
|
||||||
const bulkEditSpy = jest.spyOn(documentService, 'bulkEdit')
|
const bulkEditSpy = jest.spyOn(documentService, 'bulkEdit')
|
||||||
bulkEditSpy.mockReturnValue(of({ result: 'OK', task_id: 'workflow-1' }))
|
bulkEditSpy.mockReturnValue(of(true))
|
||||||
let openModal: NgbModalRef
|
let openModal: NgbModalRef
|
||||||
modalService.activeInstances.subscribe((modal) => (openModal = modal[0]))
|
modalService.activeInstances.subscribe((modal) => (openModal = modal[0]))
|
||||||
const toastSpy = jest.spyOn(toastService, 'show')
|
const toastSpy = jest.spyOn(toastService, 'showInfo')
|
||||||
component.runWorkflow()
|
component.runWorkflow()
|
||||||
expect(openModal.componentInstance.singleDocument).toBe(true)
|
|
||||||
expect(openModal.componentInstance.force).toBe(true)
|
|
||||||
const modalCloseSpy = jest.spyOn(openModal, 'close')
|
const modalCloseSpy = jest.spyOn(openModal, 'close')
|
||||||
openModal.componentInstance.workflowId = 5
|
openModal.componentInstance.workflowId = 5
|
||||||
|
openModal.componentInstance.force = true
|
||||||
openModal.componentInstance.confirmClicked.next()
|
openModal.componentInstance.confirmClicked.next()
|
||||||
expect(bulkEditSpy).toHaveBeenCalledWith(
|
expect(bulkEditSpy).toHaveBeenCalledWith(
|
||||||
{ documents: [doc.id] },
|
{ documents: [doc.id] },
|
||||||
'run_workflow',
|
'run_workflow',
|
||||||
{ workflow: 5, filter_documents: false }
|
{ workflow: 5, filter_documents: false }
|
||||||
)
|
)
|
||||||
jest.advanceTimersByTime(400)
|
expect(toastSpy).toHaveBeenCalled()
|
||||||
expect(toastSpy).toHaveBeenCalledWith(
|
|
||||||
expect.objectContaining({ content: 'Workflow queued.' })
|
|
||||||
)
|
|
||||||
expect(modalCloseSpy).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' }))
|
|
||||||
let openModal: NgbModalRef
|
|
||||||
modalService.activeInstances.subscribe((modal) => (openModal = modal[0]))
|
|
||||||
component.runWorkflow()
|
|
||||||
openModal.componentInstance.workflowId = 5
|
|
||||||
openModal.componentInstance.force = false
|
|
||||||
openModal.componentInstance.confirmClicked.next()
|
|
||||||
expect(bulkEditSpy).toHaveBeenCalledWith(
|
|
||||||
{ documents: [doc.id] },
|
|
||||||
'run_workflow',
|
|
||||||
{ workflow: 5, filter_documents: true }
|
|
||||||
)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should pass remote OCR choice when reprocessing', () => {
|
it('should pass remote OCR choice when reprocessing', () => {
|
||||||
initNormally()
|
initNormally()
|
||||||
const reprocessSpy = jest.spyOn(documentService, 'reprocessDocuments')
|
const reprocessSpy = jest.spyOn(documentService, 'reprocessDocuments')
|
||||||
reprocessSpy.mockReturnValue(of({ result: 'OK', task_id: 'reprocess-2' }))
|
reprocessSpy.mockReturnValue(of(true))
|
||||||
let openModal: NgbModalRef
|
let openModal: NgbModalRef
|
||||||
modalService.activeInstances.subscribe((modal) => (openModal = modal[0]))
|
modalService.activeInstances.subscribe((modal) => (openModal = modal[0]))
|
||||||
component.reprocess()
|
component.reprocess()
|
||||||
@@ -1967,282 +1930,6 @@ describe('DocumentDetailComponent', () => {
|
|||||||
expect(toastSpy).toHaveBeenCalledWith('Document reloaded.')
|
expect(toastSpy).toHaveBeenCalledWith('Document reloaded.')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should queue a chosen zone OCR template on the selected version', () => {
|
|
||||||
component.documentId.set(doc.id)
|
|
||||||
component.document.set({ ...doc, versions: docVersions })
|
|
||||||
component.selectedVersionId.set(10)
|
|
||||||
jest
|
|
||||||
.spyOn(documentService, 'runZoneOcr')
|
|
||||||
.mockReturnValue(of({ result: 'OK', task_id: 'zone-ocr-task' }))
|
|
||||||
const loadSpy = jest
|
|
||||||
.spyOn(component as any, 'loadDocument')
|
|
||||||
.mockImplementation(() => {})
|
|
||||||
const notifySpy = jest.spyOn(component.docChangeNotifier, 'next')
|
|
||||||
const queued = jest.spyOn(
|
|
||||||
TestBed.inject(TaskNotificationService),
|
|
||||||
'showQueued'
|
|
||||||
)
|
|
||||||
const modalSpy = jest.spyOn(modalService, 'open')
|
|
||||||
|
|
||||||
component.runZoneOcrWithOptions()
|
|
||||||
const dialog = modalSpy.mock.results[0].value.componentInstance
|
|
||||||
expect(dialog.message).toBe(
|
|
||||||
'Fields filled by the template will be overwritten.'
|
|
||||||
)
|
|
||||||
dialog.template = 3
|
|
||||||
dialog.confirmClicked.emit()
|
|
||||||
|
|
||||||
expect(documentService.runZoneOcr).toHaveBeenCalledWith(doc.id, 3, 10)
|
|
||||||
expect(queued).toHaveBeenCalledWith('zone-ocr-task', 'Zone OCR queued.', {
|
|
||||||
content: 'Zone OCR completed.',
|
|
||||||
})
|
|
||||||
expect(notifySpy).not.toHaveBeenCalled()
|
|
||||||
expect(loadSpy).not.toHaveBeenCalled()
|
|
||||||
expect(component.zoneOcrRunning()).toBe(false)
|
|
||||||
expect(component.networkActive()).toBe(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should queue matching templates on the latest version without a dialog', () => {
|
|
||||||
component.documentId.set(doc.id)
|
|
||||||
component.document.set({ ...doc, versions: docVersions })
|
|
||||||
component.selectedVersionId.set(12)
|
|
||||||
jest.spyOn(component as any, 'loadDocument').mockImplementation(() => {})
|
|
||||||
const runSpy = jest.spyOn(documentService, 'runZoneOcr')
|
|
||||||
const queued = jest.spyOn(
|
|
||||||
TestBed.inject(TaskNotificationService),
|
|
||||||
'showQueued'
|
|
||||||
)
|
|
||||||
const modalSpy = jest.spyOn(modalService, 'open')
|
|
||||||
|
|
||||||
runSpy.mockReturnValueOnce(
|
|
||||||
of({ result: 'OK', task_id: 'matching-zone-ocr' })
|
|
||||||
)
|
|
||||||
component.runZoneOcr()
|
|
||||||
expect(modalSpy).not.toHaveBeenCalled()
|
|
||||||
expect(runSpy).toHaveBeenCalledWith(doc.id, null, null)
|
|
||||||
expect(queued).toHaveBeenCalledWith(
|
|
||||||
'matching-zone-ocr',
|
|
||||||
'Zone OCR queued.',
|
|
||||||
{ content: 'Zone OCR completed.' }
|
|
||||||
)
|
|
||||||
expect(component.zoneOcrRunning()).toBe(false)
|
|
||||||
expect(component.networkActive()).toBe(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should discard confirmed local edits after OCR is queued', () => {
|
|
||||||
component.documentId.set(doc.id)
|
|
||||||
component.document.set({ ...doc, __changedFields: ['title'] })
|
|
||||||
component.documentForm.patchValue({ title: 'Unsaved title' })
|
|
||||||
jest
|
|
||||||
.spyOn(documentService, 'runZoneOcr')
|
|
||||||
.mockReturnValue(of({ result: 'OK', task_id: 'zone-ocr-task' }))
|
|
||||||
const modalSpy = jest.spyOn(modalService, 'open')
|
|
||||||
const load = jest
|
|
||||||
.spyOn(component as any, 'loadDocument')
|
|
||||||
.mockImplementation(() => {})
|
|
||||||
component.runZoneOcr()
|
|
||||||
modalSpy.mock.results[0].value.componentInstance.confirm()
|
|
||||||
expect(load).toHaveBeenCalledWith(doc.id, true, expect.any(Function))
|
|
||||||
load.mock.calls[0][2]()
|
|
||||||
expect(component.zoneOcrRunning()).toBe(false)
|
|
||||||
expect(component.networkActive()).toBe(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should handle task completion before the queue response', () => {
|
|
||||||
jest.useFakeTimers()
|
|
||||||
component.documentId.set(doc.id)
|
|
||||||
component.document.set({ ...doc, __changedFields: [] })
|
|
||||||
const pending = new Subject<any>()
|
|
||||||
jest.spyOn(documentService, 'runZoneOcr').mockReturnValue(pending)
|
|
||||||
const notifications = TestBed.inject(TaskNotificationService)
|
|
||||||
const toast = jest.spyOn(toastService, 'show')
|
|
||||||
component.runZoneOcr()
|
|
||||||
notifications.complete({
|
|
||||||
task_id: 'fast-zone-ocr',
|
|
||||||
operation: 'run_zone_ocr',
|
|
||||||
status: PaperlessTaskStatus.Success,
|
|
||||||
})
|
|
||||||
pending.next({ result: 'OK', task_id: 'fast-zone-ocr' })
|
|
||||||
expect(toast).toHaveBeenLastCalledWith(
|
|
||||||
expect.objectContaining({
|
|
||||||
id: 'task-fast-zone-ocr',
|
|
||||||
content: 'Zone OCR completed.',
|
|
||||||
})
|
|
||||||
)
|
|
||||||
expect(component.networkActive()).toBe(false)
|
|
||||||
pending.complete()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should refresh queued OCR changes through document update events', () => {
|
|
||||||
initNormally()
|
|
||||||
jest
|
|
||||||
.spyOn(documentService, 'runZoneOcr')
|
|
||||||
.mockReturnValue(of({ result: 'OK', task_id: 'zone-ocr-task' }))
|
|
||||||
const load = jest
|
|
||||||
.spyOn(component as any, 'loadDocument')
|
|
||||||
.mockImplementation(() => {})
|
|
||||||
component.runZoneOcr()
|
|
||||||
expect(load).not.toHaveBeenCalled()
|
|
||||||
expect(component.networkActive()).toBe(false)
|
|
||||||
|
|
||||||
TestBed.inject(WebsocketStatusService).onDocumentUpdated().next({
|
|
||||||
document_id: doc.id,
|
|
||||||
modified: '2026-02-17T00:00:00Z',
|
|
||||||
})
|
|
||||||
expect(load).toHaveBeenCalledWith(doc.id, true)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should protect edits made after OCR was queued from its document update', () => {
|
|
||||||
initNormally()
|
|
||||||
jest
|
|
||||||
.spyOn(documentService, 'runZoneOcr')
|
|
||||||
.mockReturnValue(of({ result: 'OK', task_id: 'zone-ocr-task' }))
|
|
||||||
component.runZoneOcr()
|
|
||||||
component.documentForm.patchValue({ title: 'New local edit' })
|
|
||||||
jest.spyOn(openDocumentsService, 'isDirty').mockReturnValue(true)
|
|
||||||
const conflict = jest
|
|
||||||
.spyOn(component as any, 'showIncomingUpdateModal')
|
|
||||||
.mockImplementation(() => {})
|
|
||||||
const load = jest
|
|
||||||
.spyOn(component as any, 'loadDocument')
|
|
||||||
.mockImplementation(() => {})
|
|
||||||
TestBed.inject(WebsocketStatusService).onDocumentUpdated().next({
|
|
||||||
document_id: doc.id,
|
|
||||||
modified: '2026-02-17T00:00:00Z',
|
|
||||||
})
|
|
||||||
expect(conflict).toHaveBeenCalled()
|
|
||||||
expect(load).not.toHaveBeenCalled()
|
|
||||||
expect(component.documentForm.get('title').value).toBe('New local edit')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should confirm before running zone OCR over unsaved changes', () => {
|
|
||||||
component.documentId.set(doc.id)
|
|
||||||
component.document.set({ ...doc, __changedFields: ['title'] })
|
|
||||||
component.documentForm.patchValue({ title: 'Unsaved title' })
|
|
||||||
const runSpy = jest.spyOn(documentService, 'runZoneOcr')
|
|
||||||
const modalSpy = jest.spyOn(modalService, 'open')
|
|
||||||
|
|
||||||
component.runZoneOcr()
|
|
||||||
|
|
||||||
const modal = modalSpy.mock.results[0].value
|
|
||||||
expect(modal.componentInstance.message).toBe(
|
|
||||||
'Running Zone OCR will discard them.'
|
|
||||||
)
|
|
||||||
expect(runSpy).not.toHaveBeenCalled()
|
|
||||||
modal.componentInstance.cancel()
|
|
||||||
expect(runSpy).not.toHaveBeenCalled()
|
|
||||||
expect(component.documentForm.get('title').value).toBe('Unsaved title')
|
|
||||||
expect(component.zoneOcrRunning()).toBe(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should warn about unsaved changes in the zone OCR options dialog', () => {
|
|
||||||
component.documentId.set(doc.id)
|
|
||||||
component.document.set({ ...doc, __changedFields: ['title'] })
|
|
||||||
const runSpy = jest.spyOn(documentService, 'runZoneOcr')
|
|
||||||
const modalSpy = jest.spyOn(modalService, 'open')
|
|
||||||
|
|
||||||
component.runZoneOcrWithOptions()
|
|
||||||
|
|
||||||
const dialog = modalSpy.mock.results[0].value.componentInstance
|
|
||||||
expect(dialog.message).toBe('Running Zone OCR will discard them.')
|
|
||||||
expect(dialog.btnClass).toBe('btn-warning')
|
|
||||||
dialog.cancel()
|
|
||||||
expect(runSpy).not.toHaveBeenCalled()
|
|
||||||
component.networkActive.set(true)
|
|
||||||
component.runZoneOcrWithOptions()
|
|
||||||
expect(modalSpy).toHaveBeenCalledTimes(1)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should not allow saving or a second zone OCR request while queueing', () => {
|
|
||||||
component.documentId.set(doc.id)
|
|
||||||
component.document.set({
|
|
||||||
...doc,
|
|
||||||
versions: docVersions,
|
|
||||||
__changedFields: ['title'],
|
|
||||||
})
|
|
||||||
component.selectedVersionId.set(doc.id)
|
|
||||||
const pending = new Subject<any>()
|
|
||||||
const runSpy = jest
|
|
||||||
.spyOn(documentService, 'runZoneOcr')
|
|
||||||
.mockReturnValue(pending)
|
|
||||||
const modalSpy = jest.spyOn(modalService, 'open')
|
|
||||||
|
|
||||||
component.runZoneOcr()
|
|
||||||
modalSpy.mock.results[0].value.componentInstance.confirmClicked.emit()
|
|
||||||
|
|
||||||
expect(runSpy).toHaveBeenCalledWith(doc.id, null, doc.id)
|
|
||||||
expect(component.zoneOcrRunning()).toBe(true)
|
|
||||||
expect(component.networkActive()).toBe(true)
|
|
||||||
const saveSpy = jest.spyOn(documentService, 'patch')
|
|
||||||
component.save()
|
|
||||||
expect(saveSpy).not.toHaveBeenCalled()
|
|
||||||
component.runZoneOcr()
|
|
||||||
expect(modalSpy).toHaveBeenCalledTimes(1)
|
|
||||||
expect(runSpy).toHaveBeenCalledTimes(1)
|
|
||||||
pending.error(new Error('failed'))
|
|
||||||
expect(component.zoneOcrRunning()).toBe(false)
|
|
||||||
expect(component.networkActive()).toBe(false)
|
|
||||||
expect(component.document().__changedFields).toEqual(['title'])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should not reload after zone OCR if another document is open', () => {
|
|
||||||
component.documentId.set(doc.id)
|
|
||||||
component.document.set({ ...doc, __changedFields: [] })
|
|
||||||
const pending = new Subject<any>()
|
|
||||||
jest.spyOn(documentService, 'runZoneOcr').mockReturnValue(pending)
|
|
||||||
const loadSpy = jest.spyOn(component as any, 'loadDocument')
|
|
||||||
|
|
||||||
component.runZoneOcr()
|
|
||||||
component.documentId.set(99)
|
|
||||||
pending.next({ result: 'OK', task_id: 'zone-ocr-task' })
|
|
||||||
|
|
||||||
expect(loadSpy).not.toHaveBeenCalled()
|
|
||||||
expect(component.zoneOcrRunning()).toBe(false)
|
|
||||||
pending.complete()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should keep unsaved changes when zone OCR is skipped', () => {
|
|
||||||
component.documentId.set(doc.id)
|
|
||||||
component.document.set({ ...doc, __changedFields: ['title'] })
|
|
||||||
component.documentForm.patchValue({ title: 'Unsaved title' })
|
|
||||||
const modalSpy = jest.spyOn(modalService, 'open')
|
|
||||||
jest
|
|
||||||
.spyOn(documentService, 'runZoneOcr')
|
|
||||||
.mockReturnValue(of({ result: 'skipped', reason: 'no_template' }))
|
|
||||||
const loadSpy = jest.spyOn(component as any, 'loadDocument')
|
|
||||||
const infoSpy = jest.spyOn(toastService, 'showInfo')
|
|
||||||
|
|
||||||
component.runZoneOcr()
|
|
||||||
modalSpy.mock.results[0].value.componentInstance.confirm()
|
|
||||||
|
|
||||||
expect(loadSpy).not.toHaveBeenCalled()
|
|
||||||
expect(component.documentForm.get('title').value).toBe('Unsaved title')
|
|
||||||
expect(component.zoneOcrRunning()).toBe(false)
|
|
||||||
expect(component.networkActive()).toBe(false)
|
|
||||||
expect(infoSpy).toHaveBeenCalledWith(
|
|
||||||
'No OCR template applies to this document.'
|
|
||||||
)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should show an error when zone OCR fails', () => {
|
|
||||||
component.document.set(doc)
|
|
||||||
jest
|
|
||||||
.spyOn(documentService, 'runZoneOcr')
|
|
||||||
.mockReturnValue(throwError(() => new Error('nope')))
|
|
||||||
const loadSpy = jest.spyOn(component as any, 'loadDocument')
|
|
||||||
const errorSpy = jest.spyOn(toastService, 'showError')
|
|
||||||
|
|
||||||
component.runZoneOcr()
|
|
||||||
|
|
||||||
expect(errorSpy).toHaveBeenCalledWith(
|
|
||||||
'Error running zone OCR.',
|
|
||||||
expect.any(Error)
|
|
||||||
)
|
|
||||||
expect(loadSpy).not.toHaveBeenCalled()
|
|
||||||
expect(component.zoneOcrRunning()).toBe(false)
|
|
||||||
expect(component.networkActive()).toBe(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should change preview element by render type', () => {
|
it('should change preview element by render type', () => {
|
||||||
initNormally()
|
initNormally()
|
||||||
component.document.update((document) => ({
|
component.document.update((document) => ({
|
||||||
@@ -2296,12 +1983,10 @@ describe('DocumentDetailComponent', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
it('should support pdf editor, handle error', () => {
|
it('should support pdf editor, handle error', () => {
|
||||||
jest.useFakeTimers()
|
|
||||||
let modal: NgbModalRef
|
let modal: NgbModalRef
|
||||||
modalService.activeInstances.subscribe((m) => (modal = m[0]))
|
modalService.activeInstances.subscribe((m) => (modal = m[0]))
|
||||||
const closeSpy = jest.spyOn(openDocumentsService, 'closeDocument')
|
const closeSpy = jest.spyOn(openDocumentsService, 'closeDocument')
|
||||||
const errorSpy = jest.spyOn(toastService, 'showError')
|
const errorSpy = jest.spyOn(toastService, 'showError')
|
||||||
const queuedToastSpy = jest.spyOn(toastService, 'show')
|
|
||||||
initNormally()
|
initNormally()
|
||||||
component.selectedVersionId.set(10)
|
component.selectedVersionId.set(10)
|
||||||
component.editPdf()
|
component.editPdf()
|
||||||
@@ -2320,7 +2005,6 @@ describe('DocumentDetailComponent', () => {
|
|||||||
update_document: false,
|
update_document: false,
|
||||||
include_metadata: true,
|
include_metadata: true,
|
||||||
source_mode: 'explicit_selection',
|
source_mode: 'explicit_selection',
|
||||||
from_webui: true,
|
|
||||||
})
|
})
|
||||||
req.error(new ErrorEvent('failed'))
|
req.error(new ErrorEvent('failed'))
|
||||||
expect(errorSpy).toHaveBeenCalled()
|
expect(errorSpy).toHaveBeenCalled()
|
||||||
@@ -2333,21 +2017,13 @@ describe('DocumentDetailComponent', () => {
|
|||||||
req = httpTestingController.expectOne(
|
req = httpTestingController.expectOne(
|
||||||
`${environment.apiBaseUrl}documents/edit_pdf/`
|
`${environment.apiBaseUrl}documents/edit_pdf/`
|
||||||
)
|
)
|
||||||
req.flush({ result: 'OK', task_id: 'edit-pdf-1' })
|
req.flush(true)
|
||||||
jest.advanceTimersByTime(400)
|
expect(closeSpy).toHaveBeenCalled()
|
||||||
expect(closeSpy).not.toHaveBeenCalled()
|
|
||||||
expect(queuedToastSpy).toHaveBeenCalledWith(
|
|
||||||
expect.objectContaining({ content: 'PDF edit queued.' })
|
|
||||||
)
|
|
||||||
jest.useRealTimers()
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should support removing password protection from pdfs', () => {
|
it('should support removing password protection from pdfs', () => {
|
||||||
jest.useFakeTimers()
|
|
||||||
let modal: NgbModalRef
|
let modal: NgbModalRef
|
||||||
modalService.activeInstances.subscribe((m) => (modal = m[0]))
|
modalService.activeInstances.subscribe((m) => (modal = m[0]))
|
||||||
const closeSpy = jest.spyOn(openDocumentsService, 'closeDocument')
|
|
||||||
const queuedToastSpy = jest.spyOn(toastService, 'show')
|
|
||||||
initNormally()
|
initNormally()
|
||||||
component.selectedVersionId.set(10)
|
component.selectedVersionId.set(10)
|
||||||
component.password = 'secret'
|
component.password = 'secret'
|
||||||
@@ -2368,15 +2044,8 @@ describe('DocumentDetailComponent', () => {
|
|||||||
include_metadata: false,
|
include_metadata: false,
|
||||||
delete_original: true,
|
delete_original: true,
|
||||||
source_mode: 'explicit_selection',
|
source_mode: 'explicit_selection',
|
||||||
from_webui: true,
|
|
||||||
})
|
})
|
||||||
req.flush({ result: 'OK', task_id: 'remove-password-1' })
|
req.flush(true)
|
||||||
jest.advanceTimersByTime(400)
|
|
||||||
expect(closeSpy).not.toHaveBeenCalled()
|
|
||||||
expect(queuedToastSpy).toHaveBeenCalledWith(
|
|
||||||
expect.objectContaining({ content: 'Password removal queued.' })
|
|
||||||
)
|
|
||||||
jest.useRealTimers()
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should require the current password before removing it', () => {
|
it('should require the current password before removing it', () => {
|
||||||
@@ -2428,9 +2097,9 @@ describe('DocumentDetailComponent', () => {
|
|||||||
const req = httpTestingController.expectOne(
|
const req = httpTestingController.expectOne(
|
||||||
`${environment.apiBaseUrl}documents/remove_password/`
|
`${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', () => {
|
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 { UserService } from 'src/app/services/rest/user.service'
|
||||||
import { WorkflowService } from 'src/app/services/rest/workflow.service'
|
import { WorkflowService } from 'src/app/services/rest/workflow.service'
|
||||||
import { SettingsService } from 'src/app/services/settings.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 { ToastService } from 'src/app/services/toast.service'
|
||||||
import { TrashService } from 'src/app/services/trash.service'
|
import { TrashService } from 'src/app/services/trash.service'
|
||||||
import { WebsocketStatusService } from 'src/app/services/websocket-status.service'
|
import { WebsocketStatusService } from 'src/app/services/websocket-status.service'
|
||||||
@@ -109,7 +108,6 @@ import { ConfirmDialogComponent } from '../common/confirm-dialog/confirm-dialog.
|
|||||||
import { PasswordRemovalConfirmDialogComponent } from '../common/confirm-dialog/password-removal-confirm-dialog/password-removal-confirm-dialog.component'
|
import { PasswordRemovalConfirmDialogComponent } from '../common/confirm-dialog/password-removal-confirm-dialog/password-removal-confirm-dialog.component'
|
||||||
import { ReprocessConfirmDialogComponent } from '../common/confirm-dialog/reprocess-confirm-dialog/reprocess-confirm-dialog.component'
|
import { ReprocessConfirmDialogComponent } from '../common/confirm-dialog/reprocess-confirm-dialog/reprocess-confirm-dialog.component'
|
||||||
import { RunWorkflowConfirmDialogComponent } from '../common/confirm-dialog/run-workflow-confirm-dialog/run-workflow-confirm-dialog.component'
|
import { RunWorkflowConfirmDialogComponent } from '../common/confirm-dialog/run-workflow-confirm-dialog/run-workflow-confirm-dialog.component'
|
||||||
import { ZoneOcrConfirmDialogComponent } from '../common/confirm-dialog/zone-ocr-confirm-dialog/zone-ocr-confirm-dialog.component'
|
|
||||||
import { CustomFieldsDropdownComponent } from '../common/custom-fields-dropdown/custom-fields-dropdown.component'
|
import { CustomFieldsDropdownComponent } from '../common/custom-fields-dropdown/custom-fields-dropdown.component'
|
||||||
import { CorrespondentEditDialogComponent } from '../common/edit-dialog/correspondent-edit-dialog/correspondent-edit-dialog.component'
|
import { CorrespondentEditDialogComponent } from '../common/edit-dialog/correspondent-edit-dialog/correspondent-edit-dialog.component'
|
||||||
import { DocumentTypeEditDialogComponent } from '../common/edit-dialog/document-type-edit-dialog/document-type-edit-dialog.component'
|
import { DocumentTypeEditDialogComponent } from '../common/edit-dialog/document-type-edit-dialog/document-type-edit-dialog.component'
|
||||||
@@ -228,7 +226,6 @@ export class DocumentDetailComponent
|
|||||||
private documentListViewService = inject(DocumentListViewService)
|
private documentListViewService = inject(DocumentListViewService)
|
||||||
private documentTitlePipe = inject(DocumentTitlePipe)
|
private documentTitlePipe = inject(DocumentTitlePipe)
|
||||||
private toastService = inject(ToastService)
|
private toastService = inject(ToastService)
|
||||||
private taskNotifications = inject(TaskNotificationService)
|
|
||||||
private trashService = inject(TrashService)
|
private trashService = inject(TrashService)
|
||||||
private settings = inject(SettingsService)
|
private settings = inject(SettingsService)
|
||||||
private storagePathService = inject(StoragePathService)
|
private storagePathService = inject(StoragePathService)
|
||||||
@@ -274,7 +271,6 @@ export class DocumentDetailComponent
|
|||||||
readonly error = signal<any>(undefined)
|
readonly error = signal<any>(undefined)
|
||||||
|
|
||||||
readonly networkActive = signal(false)
|
readonly networkActive = signal(false)
|
||||||
readonly zoneOcrRunning = signal(false)
|
|
||||||
|
|
||||||
readonly documentId = signal<number>(undefined)
|
readonly documentId = signal<number>(undefined)
|
||||||
readonly document = signal<Document>(undefined)
|
readonly document = signal<Document>(undefined)
|
||||||
@@ -553,11 +549,7 @@ export class DocumentDetailComponent
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
private loadDocument(
|
private loadDocument(documentId: number, forceRemote: boolean = false): void {
|
||||||
documentId: number,
|
|
||||||
forceRemote: boolean = false,
|
|
||||||
onComplete?: () => void
|
|
||||||
): void {
|
|
||||||
let redirectedToRoot = false
|
let redirectedToRoot = false
|
||||||
this.closeIncomingUpdateModal()
|
this.closeIncomingUpdateModal()
|
||||||
this.pendingIncomingUpdate = null
|
this.pendingIncomingUpdate = null
|
||||||
@@ -614,8 +606,7 @@ export class DocumentDetailComponent
|
|||||||
}),
|
}),
|
||||||
first(),
|
first(),
|
||||||
takeUntil(this.unsubscribeNotifier),
|
takeUntil(this.unsubscribeNotifier),
|
||||||
takeUntil(this.docChangeNotifier),
|
takeUntil(this.docChangeNotifier)
|
||||||
finalize(() => onComplete?.())
|
|
||||||
)
|
)
|
||||||
.subscribe({
|
.subscribe({
|
||||||
next: (doc) => {
|
next: (doc) => {
|
||||||
@@ -1363,7 +1354,6 @@ export class DocumentDetailComponent
|
|||||||
}
|
}
|
||||||
|
|
||||||
save(close: boolean = false, savedCallback: () => void = null) {
|
save(close: boolean = false, savedCallback: () => void = null) {
|
||||||
if (this.zoneOcrRunning()) return
|
|
||||||
this.networkActive.set(true)
|
this.networkActive.set(true)
|
||||||
;(document.activeElement as HTMLElement)?.dispatchEvent(new Event('change'))
|
;(document.activeElement as HTMLElement)?.dispatchEvent(new Event('change'))
|
||||||
this.documentsService
|
this.documentsService
|
||||||
@@ -1568,11 +1558,9 @@ export class DocumentDetailComponent
|
|||||||
modal.componentInstance.remoteOcr
|
modal.componentInstance.remoteOcr
|
||||||
)
|
)
|
||||||
.subscribe({
|
.subscribe({
|
||||||
next: ({ task_id }) => {
|
next: () => {
|
||||||
this.taskNotifications.showQueued(
|
this.toastService.showInfo(
|
||||||
task_id,
|
$localize`Reprocess operation for "${this.document().title}" will begin in the background.`
|
||||||
$localize`Document reprocessing queued.`,
|
|
||||||
{ content: $localize`Document submitted for reprocessing.` }
|
|
||||||
)
|
)
|
||||||
if (modal) {
|
if (modal) {
|
||||||
modal.close()
|
modal.close()
|
||||||
@@ -1599,8 +1587,6 @@ export class DocumentDetailComponent
|
|||||||
modal.componentInstance.message = $localize`Run a workflow on "${this.document().title}".`
|
modal.componentInstance.message = $localize`Run a workflow on "${this.document().title}".`
|
||||||
modal.componentInstance.btnCaption = $localize`Run`
|
modal.componentInstance.btnCaption = $localize`Run`
|
||||||
modal.componentInstance.workflows = this.manualWorkflows()
|
modal.componentInstance.workflows = this.manualWorkflows()
|
||||||
modal.componentInstance.singleDocument = true
|
|
||||||
modal.componentInstance.force = true
|
|
||||||
modal.componentInstance.confirmClicked.subscribe(() => {
|
modal.componentInstance.confirmClicked.subscribe(() => {
|
||||||
modal.componentInstance.buttonsEnabled.set(false)
|
modal.componentInstance.buttonsEnabled.set(false)
|
||||||
this.documentsService
|
this.documentsService
|
||||||
@@ -1609,13 +1595,9 @@ export class DocumentDetailComponent
|
|||||||
filter_documents: !modal.componentInstance.force,
|
filter_documents: !modal.componentInstance.force,
|
||||||
})
|
})
|
||||||
.subscribe({
|
.subscribe({
|
||||||
next: ({ task_id }) => {
|
next: () => {
|
||||||
this.taskNotifications.showQueued(
|
this.toastService.showInfo(
|
||||||
task_id,
|
$localize`Workflow will run on "${this.document().title}" in the background.`
|
||||||
$localize`Workflow queued.`,
|
|
||||||
{
|
|
||||||
content: $localize`Workflow completed.`,
|
|
||||||
}
|
|
||||||
)
|
)
|
||||||
modal.close()
|
modal.close()
|
||||||
},
|
},
|
||||||
@@ -1630,108 +1612,6 @@ export class DocumentDetailComponent
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Runs every template that matches, confirming only over unsaved changes. */
|
|
||||||
runZoneOcr() {
|
|
||||||
if (this.networkActive()) return
|
|
||||||
const documentId = this.documentId()
|
|
||||||
const versionId = this.getSelectedNonLatestVersionId()
|
|
||||||
if (!this.hasLocalEdits(this.document())) {
|
|
||||||
this.executeZoneOcr(documentId, null, versionId)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
const modal = this.modalService.open(ConfirmDialogComponent, {
|
|
||||||
backdrop: 'static',
|
|
||||||
})
|
|
||||||
modal.componentInstance.title = $localize`Run Zone OCR`
|
|
||||||
modal.componentInstance.messageBold = $localize`You have unsaved changes.`
|
|
||||||
modal.componentInstance.message = $localize`Running Zone OCR will discard them.`
|
|
||||||
modal.componentInstance.btnClass = 'btn-warning'
|
|
||||||
modal.componentInstance.btnCaption = $localize`Run Zone OCR`
|
|
||||||
modal.componentInstance.confirmClicked
|
|
||||||
.pipe(first(), takeUntil(this.unsubscribeNotifier))
|
|
||||||
.subscribe(() => {
|
|
||||||
modal.close()
|
|
||||||
if (this.documentId() === documentId && !this.networkActive()) {
|
|
||||||
this.executeZoneOcr(documentId, null, versionId)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Opens the dialog to pick which template to run. */
|
|
||||||
runZoneOcrWithOptions() {
|
|
||||||
if (this.networkActive()) return
|
|
||||||
const documentId = this.documentId()
|
|
||||||
const versionId = this.getSelectedNonLatestVersionId()
|
|
||||||
const modal = this.modalService.open(ZoneOcrConfirmDialogComponent, {
|
|
||||||
backdrop: 'static',
|
|
||||||
})
|
|
||||||
const dialog = modal.componentInstance as ZoneOcrConfirmDialogComponent
|
|
||||||
dialog.title = $localize`Run Zone OCR`
|
|
||||||
dialog.btnCaption = $localize`Run Zone OCR`
|
|
||||||
if (this.hasLocalEdits(this.document())) {
|
|
||||||
dialog.messageBold = $localize`You have unsaved changes.`
|
|
||||||
dialog.message = $localize`Running Zone OCR will discard them.`
|
|
||||||
dialog.btnClass = 'btn-warning'
|
|
||||||
} else {
|
|
||||||
dialog.message = $localize`Fields filled by the template will be overwritten.`
|
|
||||||
}
|
|
||||||
dialog.confirmClicked
|
|
||||||
.pipe(first(), takeUntil(this.unsubscribeNotifier))
|
|
||||||
.subscribe(() => {
|
|
||||||
modal.close()
|
|
||||||
if (this.documentId() === documentId && !this.networkActive()) {
|
|
||||||
this.executeZoneOcr(documentId, dialog.template, versionId)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
private executeZoneOcr(
|
|
||||||
documentId: number,
|
|
||||||
templateId: number | null,
|
|
||||||
versionId: number | null
|
|
||||||
) {
|
|
||||||
this.zoneOcrRunning.set(true)
|
|
||||||
this.networkActive.set(true)
|
|
||||||
this.documentsService
|
|
||||||
.runZoneOcr(documentId, templateId, versionId)
|
|
||||||
.pipe(takeUntil(this.unsubscribeNotifier))
|
|
||||||
.subscribe({
|
|
||||||
next: (response) => {
|
|
||||||
if (response.result === 'skipped') {
|
|
||||||
this.finishZoneOcr()
|
|
||||||
this.toastService.showInfo(
|
|
||||||
$localize`No OCR template applies to this document.`
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
this.taskNotifications.showQueued(
|
|
||||||
response.task_id,
|
|
||||||
$localize`Zone OCR queued.`,
|
|
||||||
{ content: $localize`Zone OCR completed.` }
|
|
||||||
)
|
|
||||||
if (
|
|
||||||
this.documentId() === documentId &&
|
|
||||||
this.hasLocalEdits(this.document())
|
|
||||||
) {
|
|
||||||
this.docChangeNotifier.next(documentId)
|
|
||||||
this.loadDocument(documentId, true, () => this.finishZoneOcr())
|
|
||||||
} else {
|
|
||||||
this.finishZoneOcr()
|
|
||||||
}
|
|
||||||
},
|
|
||||||
error: (error) => {
|
|
||||||
this.finishZoneOcr()
|
|
||||||
this.toastService.showError($localize`Error running zone OCR.`, error)
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
private finishZoneOcr() {
|
|
||||||
this.zoneOcrRunning.set(false)
|
|
||||||
this.networkActive.set(false)
|
|
||||||
this.flushPendingIncomingUpdate()
|
|
||||||
}
|
|
||||||
|
|
||||||
private getSelectedNonLatestVersionId(): number | null {
|
private getSelectedNonLatestVersionId(): number | null {
|
||||||
const versions = this.document()?.versions ?? []
|
const versions = this.document()?.versions ?? []
|
||||||
if (!versions.length || !this.selectedVersionId()) {
|
if (!versions.length || !this.selectedVersionId()) {
|
||||||
@@ -2107,15 +1987,14 @@ export class DocumentDetailComponent
|
|||||||
})
|
})
|
||||||
.pipe(first(), takeUntil(this.unsubscribeNotifier))
|
.pipe(first(), takeUntil(this.unsubscribeNotifier))
|
||||||
.subscribe({
|
.subscribe({
|
||||||
next: ({ task_id }) => {
|
next: () => {
|
||||||
this.taskNotifications.showQueued(
|
this.toastService.showInfo(
|
||||||
task_id,
|
$localize`PDF edit operation for "${this.document().title}" will begin in the background.`
|
||||||
$localize`PDF edit queued.`,
|
|
||||||
{
|
|
||||||
content: $localize`PDF edit submitted for processing.`,
|
|
||||||
}
|
|
||||||
)
|
)
|
||||||
modal.close()
|
modal.close()
|
||||||
|
if (modal.componentInstance.deleteOriginal) {
|
||||||
|
this.openDocumentService.closeDocument(this.document())
|
||||||
|
}
|
||||||
},
|
},
|
||||||
error: (error) => {
|
error: (error) => {
|
||||||
if (modal) {
|
if (modal) {
|
||||||
@@ -2165,16 +2044,17 @@ export class DocumentDetailComponent
|
|||||||
})
|
})
|
||||||
.pipe(first(), takeUntil(this.unsubscribeNotifier))
|
.pipe(first(), takeUntil(this.unsubscribeNotifier))
|
||||||
.subscribe({
|
.subscribe({
|
||||||
next: ({ task_id }) => {
|
next: () => {
|
||||||
this.taskNotifications.showQueued(
|
this.toastService.showInfo(
|
||||||
task_id,
|
$localize`Password removal operation for "${this.document().title}" will begin in the background.`
|
||||||
$localize`Password removal queued.`,
|
|
||||||
{
|
|
||||||
content: $localize`Password removal submitted for processing.`,
|
|
||||||
}
|
|
||||||
)
|
)
|
||||||
this.networkActive.set(false)
|
this.networkActive.set(false)
|
||||||
modal.close()
|
modal.close()
|
||||||
|
if (!dialog.updateDocument && dialog.deleteOriginal) {
|
||||||
|
this.openDocumentService.closeDocument(this.document())
|
||||||
|
} else if (dialog.updateDocument) {
|
||||||
|
this.openDocumentService.refreshDocument(this.documentId())
|
||||||
|
}
|
||||||
},
|
},
|
||||||
error: (error) => {
|
error: (error) => {
|
||||||
dialog.buttonsEnabled.set(true)
|
dialog.buttonsEnabled.set(true)
|
||||||
|
|||||||
+14
-23
@@ -2,7 +2,6 @@ import { DatePipe } from '@angular/common'
|
|||||||
import { SimpleChange, signal } from '@angular/core'
|
import { SimpleChange, signal } from '@angular/core'
|
||||||
import { ComponentFixture, TestBed } from '@angular/core/testing'
|
import { ComponentFixture, TestBed } from '@angular/core/testing'
|
||||||
import { By } from '@angular/platform-browser'
|
import { By } from '@angular/platform-browser'
|
||||||
import { Router } from '@angular/router'
|
|
||||||
import { NgbModal } from '@ng-bootstrap/ng-bootstrap'
|
import { NgbModal } from '@ng-bootstrap/ng-bootstrap'
|
||||||
import { Subject, of, throwError } from 'rxjs'
|
import { Subject, of, throwError } from 'rxjs'
|
||||||
import { DocumentVersionInfo } from 'src/app/data/document'
|
import { DocumentVersionInfo } from 'src/app/data/document'
|
||||||
@@ -34,7 +33,7 @@ describe('DocumentVersionDropdownComponent', () => {
|
|||||||
>
|
>
|
||||||
>
|
>
|
||||||
let toastService: jest.Mocked<
|
let toastService: jest.Mocked<
|
||||||
Pick<ToastService, 'show' | 'showError' | 'showInfo' | 'showSuccess'>
|
Pick<ToastService, 'showError' | 'showInfo' | 'showSuccess'>
|
||||||
>
|
>
|
||||||
let finished$: Subject<{ taskId: string }>
|
let finished$: Subject<{ taskId: string }>
|
||||||
let failed$: Subject<{ taskId: string; message?: string }>
|
let failed$: Subject<{ taskId: string; message?: string }>
|
||||||
@@ -55,7 +54,6 @@ describe('DocumentVersionDropdownComponent', () => {
|
|||||||
}
|
}
|
||||||
modalService = { open: jest.fn() }
|
modalService = { open: jest.fn() }
|
||||||
toastService = {
|
toastService = {
|
||||||
show: jest.fn(),
|
|
||||||
showError: jest.fn(),
|
showError: jest.fn(),
|
||||||
showInfo: jest.fn(),
|
showInfo: jest.fn(),
|
||||||
showSuccess: jest.fn(),
|
showSuccess: jest.fn(),
|
||||||
@@ -90,10 +88,6 @@ describe('DocumentVersionDropdownComponent', () => {
|
|||||||
provide: PermissionsService,
|
provide: PermissionsService,
|
||||||
useValue: permissionsService,
|
useValue: permissionsService,
|
||||||
},
|
},
|
||||||
{
|
|
||||||
provide: Router,
|
|
||||||
useValue: { navigate: jest.fn() },
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
provide: WebsocketStatusService,
|
provide: WebsocketStatusService,
|
||||||
useValue: {
|
useValue: {
|
||||||
@@ -383,8 +377,7 @@ describe('DocumentVersionDropdownComponent', () => {
|
|||||||
expect(component.versionLabelDraft).toEqual('')
|
expect(component.versionLabelDraft).toEqual('')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('addExistingDocumentAsVersion should queue with a label and wait to refresh versions', () => {
|
it('addExistingDocumentAsVersion should merge with a label and refresh versions', () => {
|
||||||
jest.useFakeTimers()
|
|
||||||
const confirmClicked = new Subject<number>()
|
const confirmClicked = new Subject<number>()
|
||||||
const modal = {
|
const modal = {
|
||||||
componentInstance: {
|
componentInstance: {
|
||||||
@@ -395,9 +388,14 @@ describe('DocumentVersionDropdownComponent', () => {
|
|||||||
close: jest.fn(),
|
close: jest.fn(),
|
||||||
}
|
}
|
||||||
modalService.open.mockReturnValue(modal as any)
|
modalService.open.mockReturnValue(modal as any)
|
||||||
documentService.mergeDocumentsAsVersions.mockReturnValue(
|
documentService.mergeDocumentsAsVersions.mockReturnValue(of({} as any))
|
||||||
of({ result: 'OK', task_id: 'versions-1' })
|
// 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 '
|
component.newVersionLabel = ' Imported '
|
||||||
const versionsEmitSpy = jest.spyOn(component.versionsUpdated, 'emit')
|
const versionsEmitSpy = jest.spyOn(component.versionsUpdated, 'emit')
|
||||||
const selectedEmitSpy = jest.spyOn(component.versionSelected, 'emit')
|
const selectedEmitSpy = jest.spyOn(component.versionSelected, 'emit')
|
||||||
@@ -412,18 +410,11 @@ describe('DocumentVersionDropdownComponent', () => {
|
|||||||
'Imported'
|
'Imported'
|
||||||
)
|
)
|
||||||
expect(documentService.updateVersionLabel).not.toHaveBeenCalled()
|
expect(documentService.updateVersionLabel).not.toHaveBeenCalled()
|
||||||
expect(documentService.getVersions).not.toHaveBeenCalled()
|
expect(documentService.getVersions).toHaveBeenCalledWith(3)
|
||||||
expect(versionsEmitSpy).not.toHaveBeenCalled()
|
expect(versionsEmitSpy).toHaveBeenCalledWith(versions)
|
||||||
expect(selectedEmitSpy).not.toHaveBeenCalled()
|
expect(selectedEmitSpy).toHaveBeenCalledWith(2)
|
||||||
expect(component.newVersionLabel).toEqual('')
|
expect(component.newVersionLabel).toEqual('')
|
||||||
expect(modal.close).toHaveBeenCalled()
|
expect(modal.close).toHaveBeenCalled()
|
||||||
jest.advanceTimersByTime(400)
|
expect(toastService.showSuccess).toHaveBeenCalled()
|
||||||
expect(toastService.show).toHaveBeenCalledWith(
|
|
||||||
expect.objectContaining({
|
|
||||||
content: 'Existing document queued to be added as a version.',
|
|
||||||
actionName: 'View task',
|
|
||||||
})
|
|
||||||
)
|
|
||||||
jest.useRealTimers()
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
+9
-7
@@ -28,7 +28,6 @@ import { DocumentVersionInfo } from 'src/app/data/document'
|
|||||||
import { IfPermissionsDirective } from 'src/app/directives/if-permissions.directive'
|
import { IfPermissionsDirective } from 'src/app/directives/if-permissions.directive'
|
||||||
import { CustomDatePipe } from 'src/app/pipes/custom-date.pipe'
|
import { CustomDatePipe } from 'src/app/pipes/custom-date.pipe'
|
||||||
import { DocumentService } from 'src/app/services/rest/document.service'
|
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 { ToastService } from 'src/app/services/toast.service'
|
||||||
import {
|
import {
|
||||||
UploadState,
|
UploadState,
|
||||||
@@ -78,7 +77,6 @@ export class DocumentVersionDropdownComponent
|
|||||||
private readonly toastService = inject(ToastService)
|
private readonly toastService = inject(ToastService)
|
||||||
private readonly websocketStatusService = inject(WebsocketStatusService)
|
private readonly websocketStatusService = inject(WebsocketStatusService)
|
||||||
private readonly modalService = inject(NgbModal)
|
private readonly modalService = inject(NgbModal)
|
||||||
private readonly taskNotifications = inject(TaskNotificationService)
|
|
||||||
private readonly destroy$ = new Subject<void>()
|
private readonly destroy$ = new Subject<void>()
|
||||||
private readonly documentChange$ = new Subject<void>()
|
private readonly documentChange$ = new Subject<void>()
|
||||||
|
|
||||||
@@ -307,19 +305,23 @@ export class DocumentVersionDropdownComponent
|
|||||||
versionLabel
|
versionLabel
|
||||||
)
|
)
|
||||||
.pipe(
|
.pipe(
|
||||||
|
switchMap(() => this.documentsService.getVersions(this.documentId)),
|
||||||
first(),
|
first(),
|
||||||
finalize(() => dialog.buttonsEnabled.set(true)),
|
finalize(() => dialog.buttonsEnabled.set(true)),
|
||||||
takeUntil(this.destroy$),
|
takeUntil(this.destroy$),
|
||||||
takeUntil(this.documentChange$)
|
takeUntil(this.documentChange$)
|
||||||
)
|
)
|
||||||
.subscribe({
|
.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 = ''
|
this.newVersionLabel = ''
|
||||||
modal.close()
|
modal.close()
|
||||||
this.taskNotifications.showQueued(
|
this.toastService.showSuccess(
|
||||||
task_id,
|
$localize`Existing document added as a version.`
|
||||||
$localize`Existing document queued to be added as a version.`,
|
|
||||||
{ content: $localize`Existing document added as a version.` }
|
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
error: (error) => {
|
error: (error) => {
|
||||||
|
|||||||
@@ -103,11 +103,6 @@
|
|||||||
<pngx-bs-icon name="play-circle" class="me-2"></pngx-bs-icon><ng-container i18n>Run workflow</ng-container>
|
<pngx-bs-icon name="play-circle" class="me-2"></pngx-bs-icon><ng-container i18n>Run workflow</ng-container>
|
||||||
</button>
|
</button>
|
||||||
}
|
}
|
||||||
@if (permissionService.currentUserCan(PermissionAction.View, PermissionType.OcrTemplate)) {
|
|
||||||
<button ngbDropdownItem (click)="runZoneOcrSelected()" [disabled]="!userCanEditAll">
|
|
||||||
<pngx-bs-icon name="bounding-box-circles" class="me-2"></pngx-bs-icon><ng-container i18n>Run Zone OCR</ng-container>
|
|
||||||
</button>
|
|
||||||
}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
+34
-167
@@ -14,8 +14,7 @@ import { Correspondent } from 'src/app/data/correspondent'
|
|||||||
import { CustomField, CustomFieldDataType } from 'src/app/data/custom-field'
|
import { CustomField, CustomFieldDataType } from 'src/app/data/custom-field'
|
||||||
import { DocumentType } from 'src/app/data/document-type'
|
import { DocumentType } from 'src/app/data/document-type'
|
||||||
import { FILTER_TITLE } from 'src/app/data/filter-rule-type'
|
import { FILTER_TITLE } from 'src/app/data/filter-rule-type'
|
||||||
import { PaperlessTaskStatus } from 'src/app/data/paperless-task'
|
import { Results } from 'src/app/data/results'
|
||||||
import { Results, SelectionData } from 'src/app/data/results'
|
|
||||||
import { StoragePath } from 'src/app/data/storage-path'
|
import { StoragePath } from 'src/app/data/storage-path'
|
||||||
import { Tag } from 'src/app/data/tag'
|
import { Tag } from 'src/app/data/tag'
|
||||||
import { WorkflowTriggerType } from 'src/app/data/workflow-trigger'
|
import { WorkflowTriggerType } from 'src/app/data/workflow-trigger'
|
||||||
@@ -29,7 +28,10 @@ import {
|
|||||||
import { CorrespondentService } from 'src/app/services/rest/correspondent.service'
|
import { CorrespondentService } from 'src/app/services/rest/correspondent.service'
|
||||||
import { CustomFieldsService } from 'src/app/services/rest/custom-fields.service'
|
import { CustomFieldsService } from 'src/app/services/rest/custom-fields.service'
|
||||||
import { DocumentTypeService } from 'src/app/services/rest/document-type.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 { GroupService } from 'src/app/services/rest/group.service'
|
||||||
import { ShareLinkBundleService } from 'src/app/services/rest/share-link-bundle.service'
|
import { ShareLinkBundleService } from 'src/app/services/rest/share-link-bundle.service'
|
||||||
import { StoragePathService } from 'src/app/services/rest/storage-path.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 { UserService } from 'src/app/services/rest/user.service'
|
||||||
import { WorkflowService } from 'src/app/services/rest/workflow.service'
|
import { WorkflowService } from 'src/app/services/rest/workflow.service'
|
||||||
import { SettingsService } from 'src/app/services/settings.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 { ToastService } from 'src/app/services/toast.service'
|
||||||
import { TrashService } from 'src/app/services/trash.service'
|
import { TrashService } from 'src/app/services/trash.service'
|
||||||
import { environment } from 'src/environments/environment'
|
import { environment } from 'src/environments/environment'
|
||||||
@@ -685,8 +686,6 @@ describe('BulkEditorComponent', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
it('should run a workflow on the selection via the run workflow dialog', () => {
|
it('should run a workflow on the selection via the run workflow dialog', () => {
|
||||||
const toast = jest.spyOn(toastService, 'show')
|
|
||||||
const infoToast = jest.spyOn(toastService, 'showInfo')
|
|
||||||
let modal: NgbModalRef
|
let modal: NgbModalRef
|
||||||
modalService.activeInstances.subscribe((m) => (modal = m[0]))
|
modalService.activeInstances.subscribe((m) => (modal = m[0]))
|
||||||
jest.spyOn(permissionsService, 'currentUserCan').mockReturnValue(true)
|
jest.spyOn(permissionsService, 'currentUserCan').mockReturnValue(true)
|
||||||
@@ -700,8 +699,6 @@ describe('BulkEditorComponent', () => {
|
|||||||
component.runWorkflowSelected()
|
component.runWorkflowSelected()
|
||||||
expect(modal).not.toBeUndefined()
|
expect(modal).not.toBeUndefined()
|
||||||
expect(modal.componentInstance.workflows).toEqual(component.manualWorkflows)
|
expect(modal.componentInstance.workflows).toEqual(component.manualWorkflows)
|
||||||
expect(modal.componentInstance.singleDocument).toBe(false)
|
|
||||||
expect(modal.componentInstance.force).toBe(false)
|
|
||||||
modal.componentInstance.workflowId = 5
|
modal.componentInstance.workflowId = 5
|
||||||
modal.componentInstance.force = true
|
modal.componentInstance.force = true
|
||||||
modal.componentInstance.confirm()
|
modal.componentInstance.confirm()
|
||||||
@@ -713,11 +710,7 @@ describe('BulkEditorComponent', () => {
|
|||||||
workflow: 5,
|
workflow: 5,
|
||||||
filter_documents: false,
|
filter_documents: false,
|
||||||
})
|
})
|
||||||
req.flush({ result: 'OK' })
|
req.flush(true)
|
||||||
expect(infoToast).toHaveBeenCalledWith(
|
|
||||||
'Workflow will run on the selected documents in the background.'
|
|
||||||
)
|
|
||||||
expect(toast.mock.calls.at(-1)[0].actionName).toBeUndefined()
|
|
||||||
httpTestingController.match(
|
httpTestingController.match(
|
||||||
`${environment.apiBaseUrl}documents/?page=1&page_size=50&ordering=-created&truncate_content=true&include_selection_data=true`
|
`${environment.apiBaseUrl}documents/?page=1&page_size=50&ordering=-created&truncate_content=true&include_selection_data=true`
|
||||||
) // list reload
|
) // list reload
|
||||||
@@ -726,27 +719,6 @@ describe('BulkEditorComponent', () => {
|
|||||||
) // listAllFilteredIds
|
) // listAllFilteredIds
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should require ownership of selected documents to run a workflow', () => {
|
|
||||||
component.manualWorkflows = [{ id: 5 }] as any
|
|
||||||
jest.spyOn(permissionsService, 'currentUserCan').mockReturnValue(true)
|
|
||||||
jest
|
|
||||||
.spyOn(permissionsService, 'currentUserHasObjectPermissions')
|
|
||||||
.mockReturnValue(true)
|
|
||||||
const ownsDocument = jest
|
|
||||||
.spyOn(permissionsService, 'currentUserOwnsObject')
|
|
||||||
.mockReturnValue(false)
|
|
||||||
jest
|
|
||||||
.spyOn(documentListViewService, 'documents', 'get')
|
|
||||||
.mockReturnValue([{ id: 3 }])
|
|
||||||
jest
|
|
||||||
.spyOn(documentListViewService, 'selected', 'get')
|
|
||||||
.mockReturnValue(new Set([3]))
|
|
||||||
|
|
||||||
expect(component.canRunWorkflow).toBe(false)
|
|
||||||
ownsDocument.mockReturnValue(true)
|
|
||||||
expect(component.canRunWorkflow).toBe(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should set modal dialog text accordingly for tag edit confirmation', () => {
|
it('should set modal dialog text accordingly for tag edit confirmation', () => {
|
||||||
let modal: NgbModalRef
|
let modal: NgbModalRef
|
||||||
modalService.activeInstances.subscribe((m) => (modal = m[m.length - 1]))
|
modalService.activeInstances.subscribe((m) => (modal = m[m.length - 1]))
|
||||||
@@ -1265,15 +1237,14 @@ describe('BulkEditorComponent', () => {
|
|||||||
let req = httpTestingController.expectOne(
|
let req = httpTestingController.expectOne(
|
||||||
`${environment.apiBaseUrl}documents/delete/`
|
`${environment.apiBaseUrl}documents/delete/`
|
||||||
)
|
)
|
||||||
const trackSpy = jest
|
const notifySpy = jest
|
||||||
.spyOn(trashService, 'trackMovedToTrash')
|
.spyOn(trashService, 'notifyMovedToTrash')
|
||||||
.mockImplementation(() => {})
|
.mockImplementation(() => {})
|
||||||
req.flush({ result: 'OK', task_id: 'delete-1' })
|
req.flush(true)
|
||||||
expect(req.request.body).toEqual({
|
expect(req.request.body).toEqual({
|
||||||
documents: [3, 4],
|
documents: [3, 4],
|
||||||
from_webui: true,
|
|
||||||
})
|
})
|
||||||
expect(trackSpy).toHaveBeenCalledWith('delete-1', 2, [3, 4])
|
expect(notifySpy).toHaveBeenCalledWith(expect.any(String), [3, 4])
|
||||||
httpTestingController.match(
|
httpTestingController.match(
|
||||||
`${environment.apiBaseUrl}documents/?page=1&page_size=50&ordering=-created&truncate_content=true&include_selection_data=true`
|
`${environment.apiBaseUrl}documents/?page=1&page_size=50&ordering=-created&truncate_content=true&include_selection_data=true`
|
||||||
) // list reload
|
) // list reload
|
||||||
@@ -1290,9 +1261,9 @@ describe('BulkEditorComponent', () => {
|
|||||||
req = httpTestingController.expectOne(
|
req = httpTestingController.expectOne(
|
||||||
`${environment.apiBaseUrl}documents/delete/`
|
`${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
|
// 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(
|
httpTestingController.match(
|
||||||
`${environment.apiBaseUrl}documents/?page=1&page_size=50&ordering=-created&truncate_content=true&include_selection_data=true`
|
`${environment.apiBaseUrl}documents/?page=1&page_size=50&ordering=-created&truncate_content=true&include_selection_data=true`
|
||||||
) // list reload
|
) // list reload
|
||||||
@@ -1372,11 +1343,10 @@ describe('BulkEditorComponent', () => {
|
|||||||
let req = httpTestingController.expectOne(
|
let req = httpTestingController.expectOne(
|
||||||
`${environment.apiBaseUrl}documents/reprocess/`
|
`${environment.apiBaseUrl}documents/reprocess/`
|
||||||
)
|
)
|
||||||
req.flush({ result: 'OK', task_id: 'reprocess-1' })
|
req.flush(true)
|
||||||
expect(req.request.body).toEqual({
|
expect(req.request.body).toEqual({
|
||||||
documents: [3, 4],
|
documents: [3, 4],
|
||||||
remote_ocr: false,
|
remote_ocr: false,
|
||||||
from_webui: true,
|
|
||||||
})
|
})
|
||||||
httpTestingController.match(
|
httpTestingController.match(
|
||||||
`${environment.apiBaseUrl}documents/?page=1&page_size=50&ordering=-created&truncate_content=true&include_selection_data=true`
|
`${environment.apiBaseUrl}documents/?page=1&page_size=50&ordering=-created&truncate_content=true&include_selection_data=true`
|
||||||
@@ -1386,72 +1356,7 @@ describe('BulkEditorComponent', () => {
|
|||||||
) // listAllFilteredIds
|
) // listAllFilteredIds
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should support run zone ocr', () => {
|
|
||||||
const queued = jest
|
|
||||||
.spyOn(TestBed.inject(TaskNotificationService), 'showQueued')
|
|
||||||
.mockImplementation(() => {})
|
|
||||||
const reload = jest.spyOn(documentListViewService, 'reload')
|
|
||||||
let modal: NgbModalRef
|
|
||||||
modalService.activeInstances.subscribe((m) => (modal = m[0]))
|
|
||||||
jest.spyOn(permissionsService, 'currentUserCan').mockReturnValue(true)
|
|
||||||
jest
|
|
||||||
.spyOn(documentListViewService, 'documents', 'get')
|
|
||||||
.mockReturnValue([{ id: 3 }, { id: 4 }])
|
|
||||||
jest
|
|
||||||
.spyOn(documentListViewService, 'selected', 'get')
|
|
||||||
.mockReturnValue(new Set([3, 4]))
|
|
||||||
jest
|
|
||||||
.spyOn(permissionsService, 'currentUserHasObjectPermissions')
|
|
||||||
.mockReturnValue(true)
|
|
||||||
fixture.detectChanges()
|
|
||||||
component.runZoneOcrSelected()
|
|
||||||
expect(modal).not.toBeUndefined()
|
|
||||||
modal.componentInstance.confirm()
|
|
||||||
let req = httpTestingController.expectOne(
|
|
||||||
`${environment.apiBaseUrl}documents/run_zone_ocr/`
|
|
||||||
)
|
|
||||||
req.flush({ result: 'OK', task_id: 'zone-ocr-1' })
|
|
||||||
expect(req.request.body).toEqual({
|
|
||||||
documents: [3, 4],
|
|
||||||
from_webui: true,
|
|
||||||
})
|
|
||||||
expect(queued).toHaveBeenLastCalledWith(
|
|
||||||
'zone-ocr-1',
|
|
||||||
"Bulk operation 'Run zone OCR' queued.",
|
|
||||||
{ content: "Bulk operation 'Run zone OCR' completed." }
|
|
||||||
)
|
|
||||||
expect(reload).not.toHaveBeenCalled()
|
|
||||||
|
|
||||||
component.runZoneOcrSelected()
|
|
||||||
modal.componentInstance.template = 3
|
|
||||||
modal.componentInstance.confirm()
|
|
||||||
req = httpTestingController.expectOne(
|
|
||||||
`${environment.apiBaseUrl}documents/run_zone_ocr/`
|
|
||||||
)
|
|
||||||
req.flush({ result: 'OK', task_id: 'zone-ocr-2' })
|
|
||||||
expect(req.request.body).toEqual({
|
|
||||||
documents: [3, 4],
|
|
||||||
template: 3,
|
|
||||||
from_webui: true,
|
|
||||||
})
|
|
||||||
expect(queued).toHaveBeenLastCalledWith(
|
|
||||||
'zone-ocr-2',
|
|
||||||
"Bulk operation 'Run zone OCR' queued.",
|
|
||||||
{ content: "Bulk operation 'Run zone OCR' completed." }
|
|
||||||
)
|
|
||||||
httpTestingController.match(
|
|
||||||
`${environment.apiBaseUrl}ocr_templates/?page=1&page_size=100000`
|
|
||||||
) // template list
|
|
||||||
httpTestingController.match(
|
|
||||||
`${environment.apiBaseUrl}documents/?page=1&page_size=50&ordering=-created&truncate_content=true&include_selection_data=true`
|
|
||||||
) // list reload
|
|
||||||
httpTestingController.match(
|
|
||||||
`${environment.apiBaseUrl}documents/?page=1&page_size=100000&fields=id`
|
|
||||||
) // listAllFilteredIds
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should support rotate', () => {
|
it('should support rotate', () => {
|
||||||
const toast = jest.spyOn(toastService, 'show')
|
|
||||||
let modal: NgbModalRef
|
let modal: NgbModalRef
|
||||||
modalService.activeInstances.subscribe((m) => (modal = m[0]))
|
modalService.activeInstances.subscribe((m) => (modal = m[0]))
|
||||||
jest.spyOn(permissionsService, 'currentUserCan').mockReturnValue(true)
|
jest.spyOn(permissionsService, 'currentUserCan').mockReturnValue(true)
|
||||||
@@ -1472,20 +1377,11 @@ describe('BulkEditorComponent', () => {
|
|||||||
let req = httpTestingController.expectOne(
|
let req = httpTestingController.expectOne(
|
||||||
`${environment.apiBaseUrl}documents/rotate/`
|
`${environment.apiBaseUrl}documents/rotate/`
|
||||||
)
|
)
|
||||||
req.flush({ result: 'OK', task_id: 'rotate-1' })
|
req.flush(true)
|
||||||
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."
|
|
||||||
)
|
|
||||||
expect(req.request.body).toEqual({
|
expect(req.request.body).toEqual({
|
||||||
documents: [3, 4],
|
documents: [3, 4],
|
||||||
degrees: 90,
|
degrees: 90,
|
||||||
source_mode: 'latest_version',
|
source_mode: 'latest_version',
|
||||||
from_webui: true,
|
|
||||||
})
|
})
|
||||||
httpTestingController.match(
|
httpTestingController.match(
|
||||||
`${environment.apiBaseUrl}documents/?page=1&page_size=50&ordering=-created&truncate_content=true&include_selection_data=true`
|
`${environment.apiBaseUrl}documents/?page=1&page_size=50&ordering=-created&truncate_content=true&include_selection_data=true`
|
||||||
@@ -1523,11 +1419,10 @@ describe('BulkEditorComponent', () => {
|
|||||||
let req = httpTestingController.expectOne(
|
let req = httpTestingController.expectOne(
|
||||||
`${environment.apiBaseUrl}documents/merge/`
|
`${environment.apiBaseUrl}documents/merge/`
|
||||||
)
|
)
|
||||||
req.flush({ result: 'OK', task_id: 'merge-1' })
|
req.flush(true)
|
||||||
expect(req.request.body).toEqual({
|
expect(req.request.body).toEqual({
|
||||||
documents: [3, 4],
|
documents: [3, 4],
|
||||||
metadata_document_id: 3,
|
metadata_document_id: 3,
|
||||||
from_webui: true,
|
|
||||||
})
|
})
|
||||||
httpTestingController.match(
|
httpTestingController.match(
|
||||||
`${environment.apiBaseUrl}documents/?page=1&page_size=50&ordering=-created&truncate_content=true&include_selection_data=true`
|
`${environment.apiBaseUrl}documents/?page=1&page_size=50&ordering=-created&truncate_content=true&include_selection_data=true`
|
||||||
@@ -1542,12 +1437,11 @@ describe('BulkEditorComponent', () => {
|
|||||||
req = httpTestingController.expectOne(
|
req = httpTestingController.expectOne(
|
||||||
`${environment.apiBaseUrl}documents/merge/`
|
`${environment.apiBaseUrl}documents/merge/`
|
||||||
)
|
)
|
||||||
req.flush({ result: 'OK', task_id: 'merge-2' })
|
req.flush(true)
|
||||||
expect(req.request.body).toEqual({
|
expect(req.request.body).toEqual({
|
||||||
documents: [3, 4],
|
documents: [3, 4],
|
||||||
metadata_document_id: 3,
|
metadata_document_id: 3,
|
||||||
delete_originals: true,
|
delete_originals: true,
|
||||||
from_webui: true,
|
|
||||||
})
|
})
|
||||||
httpTestingController.match(
|
httpTestingController.match(
|
||||||
`${environment.apiBaseUrl}documents/?page=1&page_size=50&ordering=-created&truncate_content=true&include_selection_data=true`
|
`${environment.apiBaseUrl}documents/?page=1&page_size=50&ordering=-created&truncate_content=true&include_selection_data=true`
|
||||||
@@ -1555,6 +1449,7 @@ describe('BulkEditorComponent', () => {
|
|||||||
httpTestingController.match(
|
httpTestingController.match(
|
||||||
`${environment.apiBaseUrl}documents/?page=1&page_size=100000&fields=id`
|
`${environment.apiBaseUrl}documents/?page=1&page_size=100000&fields=id`
|
||||||
) // listAllFilteredIds
|
) // listAllFilteredIds
|
||||||
|
expect(documentListViewService.selected.size).toEqual(0)
|
||||||
|
|
||||||
// Test with archiveFallback enabled
|
// Test with archiveFallback enabled
|
||||||
modal.componentInstance.deleteOriginals.set(false)
|
modal.componentInstance.deleteOriginals.set(false)
|
||||||
@@ -1563,12 +1458,11 @@ describe('BulkEditorComponent', () => {
|
|||||||
req = httpTestingController.expectOne(
|
req = httpTestingController.expectOne(
|
||||||
`${environment.apiBaseUrl}documents/merge/`
|
`${environment.apiBaseUrl}documents/merge/`
|
||||||
)
|
)
|
||||||
req.flush({ result: 'OK', task_id: 'merge-3' })
|
req.flush(true)
|
||||||
expect(req.request.body).toEqual({
|
expect(req.request.body).toEqual({
|
||||||
documents: [3, 4],
|
documents: [3, 4],
|
||||||
metadata_document_id: 3,
|
metadata_document_id: 3,
|
||||||
archive_fallback: true,
|
archive_fallback: true,
|
||||||
from_webui: true,
|
|
||||||
})
|
})
|
||||||
httpTestingController.match(
|
httpTestingController.match(
|
||||||
`${environment.apiBaseUrl}documents/?page=1&page_size=50&ordering=-created&truncate_content=true&include_selection_data=true`
|
`${environment.apiBaseUrl}documents/?page=1&page_size=50&ordering=-created&truncate_content=true&include_selection_data=true`
|
||||||
@@ -1576,10 +1470,10 @@ describe('BulkEditorComponent', () => {
|
|||||||
httpTestingController.match(
|
httpTestingController.match(
|
||||||
`${environment.apiBaseUrl}documents/?page=1&page_size=100000&fields=id`
|
`${environment.apiBaseUrl}documents/?page=1&page_size=100000&fields=id`
|
||||||
) // listAllFilteredIds
|
) // listAllFilteredIds
|
||||||
|
expect(documentListViewService.selected.size).toEqual(0)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should support merging documents as versions', () => {
|
it('should support merging documents as versions', () => {
|
||||||
jest.useFakeTimers()
|
|
||||||
let modal: NgbModalRef
|
let modal: NgbModalRef
|
||||||
modalService.activeInstances.subscribe((m) => (modal = m[0]))
|
modalService.activeInstances.subscribe((m) => (modal = m[0]))
|
||||||
jest.spyOn(permissionsService, 'currentUserCan').mockReturnValue(true)
|
jest.spyOn(permissionsService, 'currentUserCan').mockReturnValue(true)
|
||||||
@@ -1607,8 +1501,8 @@ describe('BulkEditorComponent', () => {
|
|||||||
.mockReturnValue(true)
|
.mockReturnValue(true)
|
||||||
const mergeAsVersionsSpy = jest
|
const mergeAsVersionsSpy = jest
|
||||||
.spyOn(documentService, 'mergeDocumentsAsVersions')
|
.spyOn(documentService, 'mergeDocumentsAsVersions')
|
||||||
.mockReturnValue(of({ result: 'OK', task_id: 'versions-1' }))
|
.mockReturnValue(of(true))
|
||||||
const toastSpy = jest.spyOn(toastService, 'show')
|
const toastSuccessSpy = jest.spyOn(toastService, 'showSuccess')
|
||||||
fixture.detectChanges()
|
fixture.detectChanges()
|
||||||
|
|
||||||
component.mergeSelectedAsVersions()
|
component.mergeSelectedAsVersions()
|
||||||
@@ -1623,21 +1517,10 @@ describe('BulkEditorComponent', () => {
|
|||||||
httpTestingController.match(
|
httpTestingController.match(
|
||||||
`${environment.apiBaseUrl}documents/?page=1&page_size=100000&fields=id`
|
`${environment.apiBaseUrl}documents/?page=1&page_size=100000&fields=id`
|
||||||
)
|
)
|
||||||
jest.advanceTimersByTime(400)
|
expect(documentListViewService.selected.size).toEqual(0)
|
||||||
expect(toastSpy).toHaveBeenCalledWith(
|
expect(toastSuccessSpy).toHaveBeenCalledWith(
|
||||||
expect.objectContaining({
|
'Documents merged as versions.'
|
||||||
content: "Bulk operation 'Merge as versions' queued.",
|
|
||||||
})
|
|
||||||
)
|
)
|
||||||
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', () => {
|
it('should not report success when merging documents as versions fails', () => {
|
||||||
@@ -1728,22 +1611,12 @@ describe('BulkEditorComponent', () => {
|
|||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
it.each<[boolean, number]>([
|
it.each([true, false])(
|
||||||
[true, 2],
|
'shows queued feedback and gates the task link on permission (%s)',
|
||||||
[false, 2],
|
(canViewTasks) => {
|
||||||
[true, 1],
|
|
||||||
])(
|
|
||||||
'names queued work and gates the task link (permission %s, documents %s)',
|
|
||||||
(canViewTasks, count) => {
|
|
||||||
jest.useFakeTimers()
|
|
||||||
jest
|
jest
|
||||||
.spyOn(permissionsService, 'currentUserCan')
|
.spyOn(permissionsService, 'currentUserCan')
|
||||||
.mockReturnValue(canViewTasks)
|
.mockReturnValue(canViewTasks)
|
||||||
jest
|
|
||||||
.spyOn(documentListViewService, 'selected', 'get')
|
|
||||||
.mockReturnValue(
|
|
||||||
new Set(Array.from({ length: count }, (_, index) => index + 3))
|
|
||||||
)
|
|
||||||
const queued = jest.spyOn(toastService, 'show')
|
const queued = jest.spyOn(toastService, 'show')
|
||||||
let modal: NgbModalRef
|
let modal: NgbModalRef
|
||||||
modalService.activeInstances.subscribe((instances) => {
|
modalService.activeInstances.subscribe((instances) => {
|
||||||
@@ -1761,11 +1634,8 @@ describe('BulkEditorComponent', () => {
|
|||||||
)
|
)
|
||||||
req.flush({ result: 'OK', task_id: 'queued-operation' })
|
req.flush({ result: 'OK', task_id: 'queued-operation' })
|
||||||
expect(close).toHaveBeenCalledTimes(1)
|
expect(close).toHaveBeenCalledTimes(1)
|
||||||
expect(queued).not.toHaveBeenCalled()
|
|
||||||
jest.advanceTimersByTime(400)
|
|
||||||
const notification = queued.mock.calls.at(-1)[0]
|
const notification = queued.mock.calls.at(-1)[0]
|
||||||
const prefix = count > 1 ? 'Bulk operation' : 'Operation'
|
expect(notification.content).toBe('Bulk operation queued.')
|
||||||
expect(notification.content).toBe(`${prefix} \'Set permissions\' queued.`)
|
|
||||||
if (canViewTasks) {
|
if (canViewTasks) {
|
||||||
expect(notification.actionName).toBe('View task')
|
expect(notification.actionName).toBe('View task')
|
||||||
notification.action()
|
notification.action()
|
||||||
@@ -1777,16 +1647,8 @@ describe('BulkEditorComponent', () => {
|
|||||||
expect(notification.actionName).toBeUndefined()
|
expect(notification.actionName).toBeUndefined()
|
||||||
}
|
}
|
||||||
expect(reload).not.toHaveBeenCalled()
|
expect(reload).not.toHaveBeenCalled()
|
||||||
|
expect(documentListViewService.selected.size).toBe(0)
|
||||||
expect(documentListViewService.allSelected).toBe(false)
|
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()
|
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -1867,6 +1729,7 @@ describe('BulkEditorComponent', () => {
|
|||||||
{ id: 2, name: 'Tag 2' },
|
{ id: 2, name: 'Tag 2' },
|
||||||
],
|
],
|
||||||
count: 2,
|
count: 2,
|
||||||
|
all: [1, 2],
|
||||||
}
|
}
|
||||||
|
|
||||||
const modalInstance = {
|
const modalInstance = {
|
||||||
@@ -1909,6 +1772,7 @@ describe('BulkEditorComponent', () => {
|
|||||||
{ id: 2, name: 'Correspondent 2' },
|
{ id: 2, name: 'Correspondent 2' },
|
||||||
],
|
],
|
||||||
count: 2,
|
count: 2,
|
||||||
|
all: [1, 2],
|
||||||
}
|
}
|
||||||
|
|
||||||
const modalInstance = {
|
const modalInstance = {
|
||||||
@@ -1957,6 +1821,7 @@ describe('BulkEditorComponent', () => {
|
|||||||
{ id: 2, name: 'Document Type 2' },
|
{ id: 2, name: 'Document Type 2' },
|
||||||
],
|
],
|
||||||
count: 2,
|
count: 2,
|
||||||
|
all: [1, 2],
|
||||||
}
|
}
|
||||||
|
|
||||||
const modalInstance = {
|
const modalInstance = {
|
||||||
@@ -2002,6 +1867,7 @@ describe('BulkEditorComponent', () => {
|
|||||||
{ id: 2, name: 'Storage Path 2' },
|
{ id: 2, name: 'Storage Path 2' },
|
||||||
],
|
],
|
||||||
count: 2,
|
count: 2,
|
||||||
|
all: [1, 2],
|
||||||
}
|
}
|
||||||
|
|
||||||
const modalInstance = {
|
const modalInstance = {
|
||||||
@@ -2055,6 +1921,7 @@ describe('BulkEditorComponent', () => {
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
count: 2,
|
count: 2,
|
||||||
|
all: [1, 2],
|
||||||
}
|
}
|
||||||
|
|
||||||
const modalInstance = {
|
const modalInstance = {
|
||||||
|
|||||||
@@ -19,18 +19,25 @@ import {
|
|||||||
NgbModalRef,
|
NgbModalRef,
|
||||||
} from '@ng-bootstrap/ng-bootstrap'
|
} from '@ng-bootstrap/ng-bootstrap'
|
||||||
import { saveAs } from 'file-saver'
|
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 { BootstrapIconComponent } from 'src/app/components/common/bootstrap-icon/bootstrap-icon.component'
|
||||||
import { ConfirmDialogComponent } from 'src/app/components/common/confirm-dialog/confirm-dialog.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 { CustomField } from 'src/app/data/custom-field'
|
||||||
import { MatchingModel } from 'src/app/data/matching-model'
|
import { MatchingModel } from 'src/app/data/matching-model'
|
||||||
import { SelectionDataItem } from 'src/app/data/results'
|
import { SelectionDataItem } from 'src/app/data/results'
|
||||||
import { SETTINGS_KEYS } from 'src/app/data/ui-settings'
|
import { SETTINGS_KEYS } from 'src/app/data/ui-settings'
|
||||||
import { Workflow } from 'src/app/data/workflow'
|
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 { IfPermissionsDirective } from 'src/app/directives/if-permissions.directive'
|
||||||
import { DocumentListViewService } from 'src/app/services/document-list-view.service'
|
import { DocumentListViewService } from 'src/app/services/document-list-view.service'
|
||||||
|
import { OpenDocumentsService } from 'src/app/services/open-documents.service'
|
||||||
import {
|
import {
|
||||||
PermissionAction,
|
PermissionAction,
|
||||||
PermissionsService,
|
PermissionsService,
|
||||||
@@ -45,18 +52,14 @@ import {
|
|||||||
DocumentService,
|
DocumentService,
|
||||||
MergeDocumentsRequest,
|
MergeDocumentsRequest,
|
||||||
} from 'src/app/services/rest/document.service'
|
} 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 { 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 { StoragePathService } from 'src/app/services/rest/storage-path.service'
|
||||||
import { TagService } from 'src/app/services/rest/tag.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 { 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 { ToastService } from 'src/app/services/toast.service'
|
||||||
import { TrashService } from 'src/app/services/trash.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 { flattenTags } from 'src/app/utils/flatten-tags'
|
||||||
import { queryParamsFromFilterRules } from 'src/app/utils/query-params'
|
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'
|
import { MergeAsVersionsConfirmDialogComponent } from '../../common/confirm-dialog/merge-as-versions-confirm-dialog/merge-as-versions-confirm-dialog.component'
|
||||||
@@ -64,7 +67,6 @@ import { MergeConfirmDialogComponent } from '../../common/confirm-dialog/merge-c
|
|||||||
import { ReprocessConfirmDialogComponent } from '../../common/confirm-dialog/reprocess-confirm-dialog/reprocess-confirm-dialog.component'
|
import { ReprocessConfirmDialogComponent } from '../../common/confirm-dialog/reprocess-confirm-dialog/reprocess-confirm-dialog.component'
|
||||||
import { RotateConfirmDialogComponent } from '../../common/confirm-dialog/rotate-confirm-dialog/rotate-confirm-dialog.component'
|
import { RotateConfirmDialogComponent } from '../../common/confirm-dialog/rotate-confirm-dialog/rotate-confirm-dialog.component'
|
||||||
import { RunWorkflowConfirmDialogComponent } from '../../common/confirm-dialog/run-workflow-confirm-dialog/run-workflow-confirm-dialog.component'
|
import { RunWorkflowConfirmDialogComponent } from '../../common/confirm-dialog/run-workflow-confirm-dialog/run-workflow-confirm-dialog.component'
|
||||||
import { ZoneOcrConfirmDialogComponent } from '../../common/confirm-dialog/zone-ocr-confirm-dialog/zone-ocr-confirm-dialog.component'
|
|
||||||
import { CorrespondentEditDialogComponent } from '../../common/edit-dialog/correspondent-edit-dialog/correspondent-edit-dialog.component'
|
import { CorrespondentEditDialogComponent } from '../../common/edit-dialog/correspondent-edit-dialog/correspondent-edit-dialog.component'
|
||||||
import { CustomFieldEditDialogComponent } from '../../common/edit-dialog/custom-field-edit-dialog/custom-field-edit-dialog.component'
|
import { CustomFieldEditDialogComponent } from '../../common/edit-dialog/custom-field-edit-dialog/custom-field-edit-dialog.component'
|
||||||
import { DocumentTypeEditDialogComponent } from '../../common/edit-dialog/document-type-edit-dialog/document-type-edit-dialog.component'
|
import { DocumentTypeEditDialogComponent } from '../../common/edit-dialog/document-type-edit-dialog/document-type-edit-dialog.component'
|
||||||
@@ -82,6 +84,7 @@ import { PermissionsDialogComponent } from '../../common/permissions-dialog/perm
|
|||||||
import { ShareLinkBundleDialogComponent } from '../../common/share-link-bundle-dialog/share-link-bundle-dialog.component'
|
import { ShareLinkBundleDialogComponent } from '../../common/share-link-bundle-dialog/share-link-bundle-dialog.component'
|
||||||
import { ComponentWithPermissions } from '../../with-permissions/with-permissions.component'
|
import { ComponentWithPermissions } from '../../with-permissions/with-permissions.component'
|
||||||
import { CustomFieldsBulkEditDialogComponent } from './custom-fields-bulk-edit-dialog/custom-fields-bulk-edit-dialog.component'
|
import { CustomFieldsBulkEditDialogComponent } from './custom-fields-bulk-edit-dialog/custom-fields-bulk-edit-dialog.component'
|
||||||
|
import { WorkflowTriggerType } from 'src/app/data/workflow-trigger'
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'pngx-bulk-editor',
|
selector: 'pngx-bulk-editor',
|
||||||
@@ -107,12 +110,13 @@ export class BulkEditorComponent
|
|||||||
private documentService = inject(DocumentService)
|
private documentService = inject(DocumentService)
|
||||||
private trashService = inject(TrashService)
|
private trashService = inject(TrashService)
|
||||||
private modalService = inject(NgbModal)
|
private modalService = inject(NgbModal)
|
||||||
|
private openDocumentService = inject(OpenDocumentsService)
|
||||||
private settings = inject(SettingsService)
|
private settings = inject(SettingsService)
|
||||||
private toastService = inject(ToastService)
|
private toastService = inject(ToastService)
|
||||||
private taskNotifications = inject(TaskNotificationService)
|
|
||||||
private storagePathService = inject(StoragePathService)
|
private storagePathService = inject(StoragePathService)
|
||||||
private customFieldService = inject(CustomFieldsService)
|
private customFieldService = inject(CustomFieldsService)
|
||||||
public readonly permissionService = inject(PermissionsService)
|
public readonly permissionService = inject(PermissionsService)
|
||||||
|
private savedViewService = inject(SavedViewService)
|
||||||
private readonly shareLinkBundleService = inject(ShareLinkBundleService)
|
private readonly shareLinkBundleService = inject(ShareLinkBundleService)
|
||||||
private readonly workflowService = inject(WorkflowService)
|
private readonly workflowService = inject(WorkflowService)
|
||||||
private readonly router = inject(Router)
|
private readonly router = inject(Router)
|
||||||
@@ -304,9 +308,7 @@ export class BulkEditorComponent
|
|||||||
}
|
}
|
||||||
|
|
||||||
get canRunWorkflow(): boolean {
|
get canRunWorkflow(): boolean {
|
||||||
return (
|
return this.userCanEditAll && this.manualWorkflows.length > 0
|
||||||
this.userCanEditAll && this.userOwnsAll && this.manualWorkflows.length > 0
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
runWorkflowSelected() {
|
runWorkflowSelected() {
|
||||||
@@ -320,22 +322,10 @@ export class BulkEditorComponent
|
|||||||
modal.componentInstance.confirmClicked
|
modal.componentInstance.confirmClicked
|
||||||
.pipe(takeUntil(this.unsubscribeNotifier))
|
.pipe(takeUntil(this.unsubscribeNotifier))
|
||||||
.subscribe(() => {
|
.subscribe(() => {
|
||||||
modal.componentInstance.buttonsEnabled.set(false)
|
this.executeBulkEditMethod(modal, 'run_workflow', {
|
||||||
this.documentService
|
workflow: modal.componentInstance.workflowId,
|
||||||
.bulkEdit(this.getSelectionQuery(), 'run_workflow', {
|
filter_documents: !modal.componentInstance.force,
|
||||||
workflow: modal.componentInstance.workflowId,
|
})
|
||||||
filter_documents: !modal.componentInstance.force,
|
|
||||||
})
|
|
||||||
.pipe(first())
|
|
||||||
.subscribe({
|
|
||||||
next: () => {
|
|
||||||
modal.close()
|
|
||||||
this.toastService.showInfo(
|
|
||||||
$localize`Workflow will run on the selected documents in the background.`
|
|
||||||
)
|
|
||||||
},
|
|
||||||
error: (error) => this.handleOperationError(modal, error),
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -352,61 +342,70 @@ export class BulkEditorComponent
|
|||||||
.bulkEdit(overrideSelection ?? this.getSelectionQuery(), method, args)
|
.bulkEdit(overrideSelection ?? this.getSelectionQuery(), method, args)
|
||||||
.pipe(first())
|
.pipe(first())
|
||||||
.subscribe({
|
.subscribe({
|
||||||
next: ({ task_id }) =>
|
next: ({ task_id }) => this.handleOperationQueued(modal, task_id),
|
||||||
this.handleOperationQueued(modal, task_id, method),
|
|
||||||
error: (error) => this.handleOperationError(modal, error),
|
error: (error) => this.handleOperationError(modal, error),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
private handleOperationQueued(
|
private handleOperationQueued(modal: NgbModalRef, taskId: string) {
|
||||||
modal: NgbModalRef,
|
|
||||||
taskId: string,
|
|
||||||
operation: string,
|
|
||||||
onQueued?: (taskId: string) => void
|
|
||||||
) {
|
|
||||||
const bulk = this.getSelectionSize() > 1
|
|
||||||
modal?.close()
|
modal?.close()
|
||||||
if (onQueued) {
|
this.list.selectNone()
|
||||||
onQueued(taskId)
|
const canViewTasks = this.permissionService.currentUserCan(
|
||||||
} else {
|
PermissionAction.View,
|
||||||
const label = getDocumentOperationLabel(operation)
|
PermissionType.PaperlessTask
|
||||||
const submittedMessage = bulk
|
)
|
||||||
? $localize`Bulk operation '${label}' submitted for processing.`
|
this.toastService.show({
|
||||||
: $localize`Operation '${label}' submitted for processing.`
|
content: $localize`Bulk operation queued.`,
|
||||||
const completedMessage = bulk
|
delay: 5000,
|
||||||
? $localize`Bulk operation '${label}' completed.`
|
...(canViewTasks
|
||||||
: $localize`Operation '${label}' completed.`
|
? {
|
||||||
this.taskNotifications.showQueued(
|
actionName: $localize`View task`,
|
||||||
taskId,
|
action: () =>
|
||||||
bulk
|
this.router.navigate(['/tasks'], {
|
||||||
? $localize`Bulk operation '${label}' queued.`
|
queryParams: { task_id: taskId },
|
||||||
: $localize`Operation '${label}' queued.`,
|
}),
|
||||||
{
|
}
|
||||||
content: documentOperationHasFollowUpTasks(operation)
|
: {}),
|
||||||
? submittedMessage
|
})
|
||||||
: completedMessage,
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private executeDocumentAction(
|
private executeDocumentAction(
|
||||||
modal: NgbModalRef,
|
modal: NgbModalRef,
|
||||||
operation: string,
|
request: Observable<any>,
|
||||||
request: Observable<BulkOperationResponse>,
|
options: { clearSelection?: boolean; successMessage?: string } = {}
|
||||||
onQueued?: (taskId: string) => void
|
|
||||||
) {
|
) {
|
||||||
if (modal) {
|
if (modal) {
|
||||||
modal.componentInstance.buttonsEnabled.set(false)
|
modal.componentInstance.buttonsEnabled.set(false)
|
||||||
}
|
}
|
||||||
request.pipe(first()).subscribe({
|
request.pipe(first()).subscribe({
|
||||||
next: ({ task_id }) => {
|
next: () => {
|
||||||
this.handleOperationQueued(modal, task_id, operation, onQueued)
|
this.handleOperationSuccess(modal, options.clearSelection ?? false)
|
||||||
|
if (options.successMessage) {
|
||||||
|
this.toastService.showSuccess(options.successMessage)
|
||||||
|
}
|
||||||
},
|
},
|
||||||
error: (error) => this.handleOperationError(modal, error),
|
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) {
|
private handleOperationError(modal: NgbModalRef, error: any) {
|
||||||
if (modal) {
|
if (modal) {
|
||||||
modal.componentInstance.buttonsEnabled.set(true)
|
modal.componentInstance.buttonsEnabled.set(true)
|
||||||
@@ -974,9 +973,16 @@ export class BulkEditorComponent
|
|||||||
const count = this.getSelectionSize()
|
const count = this.getSelectionSize()
|
||||||
this.executeDocumentAction(
|
this.executeDocumentAction(
|
||||||
modal,
|
modal,
|
||||||
'delete',
|
this.documentService
|
||||||
this.documentService.deleteDocuments(this.getSelectionQuery()),
|
.deleteDocuments(this.getSelectionQuery())
|
||||||
(taskId) => this.trashService.trackMovedToTrash(taskId, count, documents)
|
.pipe(
|
||||||
|
tap(() =>
|
||||||
|
this.trashService.notifyMovedToTrash(
|
||||||
|
$localize`Moved ${count} document(s) to the trash`,
|
||||||
|
documents
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1017,7 +1023,6 @@ export class BulkEditorComponent
|
|||||||
modal.componentInstance.buttonsEnabled.set(false)
|
modal.componentInstance.buttonsEnabled.set(false)
|
||||||
this.executeDocumentAction(
|
this.executeDocumentAction(
|
||||||
modal,
|
modal,
|
||||||
'reprocess',
|
|
||||||
this.documentService.reprocessDocuments(
|
this.documentService.reprocessDocuments(
|
||||||
this.getSelectionQuery(),
|
this.getSelectionQuery(),
|
||||||
modal.componentInstance.remoteOcr
|
modal.componentInstance.remoteOcr
|
||||||
@@ -1026,31 +1031,6 @@ export class BulkEditorComponent
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
runZoneOcrSelected() {
|
|
||||||
const modal = this.modalService.open(ZoneOcrConfirmDialogComponent, {
|
|
||||||
backdrop: 'static',
|
|
||||||
})
|
|
||||||
const dialog = modal.componentInstance as ZoneOcrConfirmDialogComponent
|
|
||||||
dialog.title = $localize`Run zone OCR confirm`
|
|
||||||
dialog.messageBold = $localize`This operation will run zone OCR on ${this.getSelectionSize()} selected document(s).`
|
|
||||||
dialog.message = $localize`Fields filled by the template will be overwritten.`
|
|
||||||
dialog.btnClass = 'btn-warning'
|
|
||||||
dialog.btnCaption = $localize`Proceed`
|
|
||||||
dialog.confirmClicked
|
|
||||||
.pipe(takeUntil(this.unsubscribeNotifier))
|
|
||||||
.subscribe(() => {
|
|
||||||
dialog.buttonsEnabled.set(false)
|
|
||||||
this.executeDocumentAction(
|
|
||||||
modal,
|
|
||||||
'run_zone_ocr',
|
|
||||||
this.documentService.runZoneOcrDocuments(
|
|
||||||
this.getSelectionQuery(),
|
|
||||||
dialog.template
|
|
||||||
)
|
|
||||||
)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
setPermissions() {
|
setPermissions() {
|
||||||
let modal = this.modalService.open(PermissionsDialogComponent, {
|
let modal = this.modalService.open(PermissionsDialogComponent, {
|
||||||
backdrop: 'static',
|
backdrop: 'static',
|
||||||
@@ -1083,7 +1063,6 @@ export class BulkEditorComponent
|
|||||||
rotateDialog.buttonsEnabled.set(false)
|
rotateDialog.buttonsEnabled.set(false)
|
||||||
this.executeDocumentAction(
|
this.executeDocumentAction(
|
||||||
modal,
|
modal,
|
||||||
'rotate',
|
|
||||||
this.documentService.rotateDocuments(
|
this.documentService.rotateDocuments(
|
||||||
this.getSelectionQuery(),
|
this.getSelectionQuery(),
|
||||||
rotateDialog.degrees
|
rotateDialog.degrees
|
||||||
@@ -1117,8 +1096,11 @@ export class BulkEditorComponent
|
|||||||
mergeDialog.buttonsEnabled.set(false)
|
mergeDialog.buttonsEnabled.set(false)
|
||||||
this.executeDocumentAction(
|
this.executeDocumentAction(
|
||||||
modal,
|
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.`
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -1140,11 +1122,14 @@ export class BulkEditorComponent
|
|||||||
.subscribe(() => {
|
.subscribe(() => {
|
||||||
this.executeDocumentAction(
|
this.executeDocumentAction(
|
||||||
modal,
|
modal,
|
||||||
'merge_as_versions',
|
|
||||||
this.documentService.mergeDocumentsAsVersions(
|
this.documentService.mergeDocumentsAsVersions(
|
||||||
mergeDialog.documentIDs(),
|
mergeDialog.documentIDs(),
|
||||||
mergeDialog.rootDocumentID()
|
mergeDialog.rootDocumentID()
|
||||||
)
|
),
|
||||||
|
{
|
||||||
|
clearSelection: true,
|
||||||
|
successMessage: $localize`Documents merged as versions.`,
|
||||||
|
}
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -1169,7 +1154,7 @@ export class BulkEditorComponent
|
|||||||
dialog.selection = this.getSelectionQuery()
|
dialog.selection = this.getSelectionQuery()
|
||||||
dialog.selectionCount = this.getSelectionSize()
|
dialog.selectionCount = this.getSelectionSize()
|
||||||
dialog.succeeded.subscribe(({ task_id }) =>
|
dialog.succeeded.subscribe(({ task_id }) =>
|
||||||
this.handleOperationQueued(null, task_id, 'modify_custom_fields')
|
this.handleOperationQueued(null, task_id)
|
||||||
)
|
)
|
||||||
dialog.failed.subscribe((error) => {
|
dialog.failed.subscribe((error) => {
|
||||||
this.toastService.showError(
|
this.toastService.showError(
|
||||||
|
|||||||
+2
-6
@@ -36,12 +36,8 @@
|
|||||||
{{document().title | documentTitle}}
|
{{document().title | documentTitle}}
|
||||||
}
|
}
|
||||||
@if (displayFields().includes(DisplayField.TAGS)) {
|
@if (displayFields().includes(DisplayField.TAGS)) {
|
||||||
@let tags = document().tags | displayTags | async;
|
@for (tagID of document().tags; track tagID) {
|
||||||
@for (tagID of tags?.visible; track tagID) {
|
<pngx-tag [tagID]="tagID" linkTitle="Filter by tag" i18n-linkTitle class="ms-1" (click)="clickTag.emit(tagID);$event.stopPropagation()" [clickable]="clickTag.observers.length"></pngx-tag>
|
||||||
<pngx-tag [tagID]="tagID" [split]="true" linkTitle="Filter by tag" i18n-linkTitle class="ms-1" (click)="clickTag.emit(tagID);$event.stopPropagation()" (parentClick)="clickTag.emit($event)" [clickable]="clickTag.observers.length"></pngx-tag>
|
|
||||||
}
|
|
||||||
@if (tags?.hidden.length) {
|
|
||||||
<pngx-hidden-tags-badge [count]="tags.hidden.length" class="ms-1"></pngx-hidden-tags-badge>
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} @else {
|
} @else {
|
||||||
|
|||||||
-4
@@ -1,4 +1,3 @@
|
|||||||
import { HiddenTagsBadgeComponent } from 'src/app/components/common/hidden-tags-badge/hidden-tags-badge.component'
|
|
||||||
import { AsyncPipe, NgOptimizedImage } from '@angular/common'
|
import { AsyncPipe, NgOptimizedImage } from '@angular/common'
|
||||||
import {
|
import {
|
||||||
AfterViewInit,
|
AfterViewInit,
|
||||||
@@ -21,7 +20,6 @@ import {
|
|||||||
Document,
|
Document,
|
||||||
} from 'src/app/data/document'
|
} from 'src/app/data/document'
|
||||||
import { SETTINGS_KEYS } from 'src/app/data/ui-settings'
|
import { SETTINGS_KEYS } from 'src/app/data/ui-settings'
|
||||||
import { DisplayTagsPipe } from 'src/app/pipes/display-tags.pipe'
|
|
||||||
import { CorrespondentNamePipe } from 'src/app/pipes/correspondent-name.pipe'
|
import { CorrespondentNamePipe } from 'src/app/pipes/correspondent-name.pipe'
|
||||||
import { CustomDatePipe } from 'src/app/pipes/custom-date.pipe'
|
import { CustomDatePipe } from 'src/app/pipes/custom-date.pipe'
|
||||||
import { DocumentTitlePipe } from 'src/app/pipes/document-title.pipe'
|
import { DocumentTitlePipe } from 'src/app/pipes/document-title.pipe'
|
||||||
@@ -47,8 +45,6 @@ import { LoadingComponentWithPermissions } from '../../loading-component/loading
|
|||||||
TagComponent,
|
TagComponent,
|
||||||
CustomFieldDisplayComponent,
|
CustomFieldDisplayComponent,
|
||||||
AsyncPipe,
|
AsyncPipe,
|
||||||
DisplayTagsPipe,
|
|
||||||
HiddenTagsBadgeComponent,
|
|
||||||
NgOptimizedImage,
|
NgOptimizedImage,
|
||||||
UsernamePipe,
|
UsernamePipe,
|
||||||
CorrespondentNamePipe,
|
CorrespondentNamePipe,
|
||||||
|
|||||||
+4
-10
@@ -19,21 +19,15 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
@if (document() && displayFields().includes(DisplayField.TAGS)) {
|
@if (document() && displayFields().includes(DisplayField.TAGS)) {
|
||||||
@let tags = document().tags | displayTags | async;
|
<div class="tags d-flex flex-column text-end position-absolute me-1 fs-6" [class.tags-no-wrap]="document().tags.length > 3">
|
||||||
@let visibleTagIDs = tags?.visible;
|
@for (tagID of tagIDs; track tagID) {
|
||||||
@let showHidden = showHiddenTags(tags);
|
<pngx-tag [tagID]="tagID" (click)="clickTag.emit(tagID);$event.stopPropagation()" [clickable]="true" linkTitle="Toggle tag filter" i18n-linkTitle></pngx-tag>
|
||||||
<div class="tags d-flex flex-column text-end position-absolute me-1 fs-6" [class.tags-no-wrap]="(visibleTagIDs?.length ?? 0) + (showHidden ? 1 : 0) > 3">
|
|
||||||
@for (tagID of getTagIDs(visibleTagIDs); track tagID) {
|
|
||||||
<pngx-tag [tagID]="tagID" [split]="true" (click)="clickTag.emit(tagID);$event.stopPropagation()" (parentClick)="clickTag.emit($event)" [clickable]="true" linkTitle="Toggle tag filter" i18n-linkTitle></pngx-tag>
|
|
||||||
}
|
}
|
||||||
@if (getMoreTags(visibleTagIDs); as moreTags) {
|
@if (moreTags) {
|
||||||
<div>
|
<div>
|
||||||
<span class="badge text-dark">+ {{moreTags}}</span>
|
<span class="badge text-dark">+ {{moreTags}}</span>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
@if (showHidden) {
|
|
||||||
<pngx-hidden-tags-badge [count]="tags.hidden.length"></pngx-hidden-tags-badge>
|
|
||||||
}
|
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
+1
-2
@@ -103,8 +103,7 @@ a {
|
|||||||
line-height: 1;
|
line-height: 1;
|
||||||
|
|
||||||
&.tags-no-wrap {
|
&.tags-no-wrap {
|
||||||
// split-pill parents clip to a stub instead (see TagComponent)
|
::ng-deep .badge {
|
||||||
::ng-deep .badge:not(.split-parent) {
|
|
||||||
display: inline-block;
|
display: inline-block;
|
||||||
max-width: 100%;
|
max-width: 100%;
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
|
|||||||
+2
-75
@@ -4,9 +4,6 @@ import { provideHttpClientTesting } from '@angular/common/http/testing'
|
|||||||
import { ComponentFixture, TestBed } from '@angular/core/testing'
|
import { ComponentFixture, TestBed } from '@angular/core/testing'
|
||||||
import { By } from '@angular/platform-browser'
|
import { By } from '@angular/platform-browser'
|
||||||
import { RouterTestingModule } from '@angular/router/testing'
|
import { RouterTestingModule } from '@angular/router/testing'
|
||||||
import { of } from 'rxjs'
|
|
||||||
import { PermissionsService } from 'src/app/services/permissions.service'
|
|
||||||
import { TagService } from 'src/app/services/rest/tag.service'
|
|
||||||
import { TagComponent } from '../../common/tag/tag.component'
|
import { TagComponent } from '../../common/tag/tag.component'
|
||||||
import { DocumentCardSmallComponent } from './document-card-small.component'
|
import { DocumentCardSmallComponent } from './document-card-small.component'
|
||||||
|
|
||||||
@@ -42,19 +39,6 @@ describe('DocumentCardSmallComponent', () => {
|
|||||||
],
|
],
|
||||||
}).compileComponents()
|
}).compileComponents()
|
||||||
|
|
||||||
jest
|
|
||||||
.spyOn(TestBed.inject(PermissionsService), 'currentUserCan')
|
|
||||||
.mockReturnValue(true)
|
|
||||||
jest.spyOn(TestBed.inject(TagService), 'listAll').mockReturnValue(
|
|
||||||
of({
|
|
||||||
count: 8,
|
|
||||||
all: [1, 2, 3, 4, 5, 6, 7, 8],
|
|
||||||
results: [1, 2, 3, 4, 5, 6, 7, 8].map((id) => ({
|
|
||||||
id,
|
|
||||||
name: `Tag ${id}`,
|
|
||||||
})),
|
|
||||||
})
|
|
||||||
)
|
|
||||||
fixture = TestBed.createComponent(DocumentCardSmallComponent)
|
fixture = TestBed.createComponent(DocumentCardSmallComponent)
|
||||||
component = fixture.componentInstance
|
component = fixture.componentInstance
|
||||||
fixture.componentRef.setInput('document', Object.assign({}, doc))
|
fixture.componentRef.setInput('document', Object.assign({}, doc))
|
||||||
@@ -113,36 +97,8 @@ describe('DocumentCardSmallComponent', () => {
|
|||||||
).toHaveLength(6)
|
).toHaveLength(6)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should hide parent tags implied by a child and count pills for the hidden tag counter', () => {
|
|
||||||
jest
|
|
||||||
.spyOn(TestBed.inject(PermissionsService), 'currentUserCan')
|
|
||||||
.mockReturnValue(true)
|
|
||||||
jest.spyOn(TestBed.inject(TagService), 'listAll').mockReturnValue(
|
|
||||||
of({
|
|
||||||
count: 8,
|
|
||||||
all: [1, 2, 3, 4, 5, 6, 7, 8],
|
|
||||||
results: [
|
|
||||||
{ id: 1, name: 'Parent' },
|
|
||||||
{ id: 2, name: 'Child', parent: 1 },
|
|
||||||
...[3, 4, 5, 6, 7, 8].map((id) => ({ id, name: `Tag ${id}` })),
|
|
||||||
],
|
|
||||||
})
|
|
||||||
)
|
|
||||||
fixture.componentRef.setInput('document', {
|
|
||||||
...component.document(),
|
|
||||||
tags: [1, 2, 3, 4, 5, 6, 7, 8],
|
|
||||||
})
|
|
||||||
fixture.detectChanges()
|
|
||||||
|
|
||||||
const tags = fixture.debugElement.queryAll(By.directive(TagComponent))
|
|
||||||
expect(tags.map((t) => t.componentInstance.tagID())).toEqual([
|
|
||||||
2, 3, 4, 5, 6,
|
|
||||||
])
|
|
||||||
expect(fixture.nativeElement.textContent).toContain('+ 2')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should clear hidden tag counter when tag count falls below the limit', () => {
|
it('should clear hidden tag counter when tag count falls below the limit', () => {
|
||||||
expect(component.getMoreTags(component.document().tags)).toEqual(3)
|
expect(component.moreTags).toEqual(3)
|
||||||
|
|
||||||
fixture.componentRef.setInput('document', {
|
fixture.componentRef.setInput('document', {
|
||||||
...component.document(),
|
...component.document(),
|
||||||
@@ -150,7 +106,7 @@ describe('DocumentCardSmallComponent', () => {
|
|||||||
})
|
})
|
||||||
fixture.detectChanges()
|
fixture.detectChanges()
|
||||||
|
|
||||||
expect(component.getMoreTags(component.document().tags)).toBeNull()
|
expect(component.moreTags).toBeNull()
|
||||||
expect(fixture.nativeElement.textContent).not.toContain('+ 3')
|
expect(fixture.nativeElement.textContent).not.toContain('+ 3')
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -161,33 +117,4 @@ describe('DocumentCardSmallComponent', () => {
|
|||||||
component.mouseLeaveCard()
|
component.mouseLeaveCard()
|
||||||
expect(component.popupPreview.close).toHaveBeenCalled()
|
expect(component.popupPreview.close).toHaveBeenCalled()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should show hidden tags last, only when visible tags leave a slot free', () => {
|
|
||||||
fixture.componentRef.setInput('document', {
|
|
||||||
...component.document(),
|
|
||||||
tags: [1, 2, 3, 98, 99],
|
|
||||||
})
|
|
||||||
fixture.detectChanges()
|
|
||||||
const tagsEl = () => fixture.nativeElement.querySelector('.tags')
|
|
||||||
expect(tagsEl().lastElementChild.textContent).toContain('2 hidden')
|
|
||||||
|
|
||||||
// 6 visible tags fill the limit (document has notes)
|
|
||||||
fixture.componentRef.setInput('document', {
|
|
||||||
...component.document(),
|
|
||||||
tags: [1, 2, 3, 4, 5, 6, 98, 99],
|
|
||||||
})
|
|
||||||
fixture.detectChanges()
|
|
||||||
expect(tagsEl().textContent).not.toContain('hidden')
|
|
||||||
expect(
|
|
||||||
fixture.debugElement.queryAll(By.directive(TagComponent))
|
|
||||||
).toHaveLength(6)
|
|
||||||
|
|
||||||
fixture.componentRef.setInput('document', {
|
|
||||||
...component.document(),
|
|
||||||
tags: [1, 2, 3, 4, 5, 6, 7, 98],
|
|
||||||
})
|
|
||||||
fixture.detectChanges()
|
|
||||||
expect(tagsEl().textContent).toContain('+ 2')
|
|
||||||
expect(tagsEl().textContent).not.toContain('hidden')
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
+14
-22
@@ -1,5 +1,3 @@
|
|||||||
import { TagPartition } from 'src/app/utils/tag-display'
|
|
||||||
import { HiddenTagsBadgeComponent } from 'src/app/components/common/hidden-tags-badge/hidden-tags-badge.component'
|
|
||||||
import { AsyncPipe, NgOptimizedImage } from '@angular/common'
|
import { AsyncPipe, NgOptimizedImage } from '@angular/common'
|
||||||
import {
|
import {
|
||||||
AfterViewInit,
|
AfterViewInit,
|
||||||
@@ -22,7 +20,6 @@ import {
|
|||||||
Document,
|
Document,
|
||||||
} from 'src/app/data/document'
|
} from 'src/app/data/document'
|
||||||
import { SETTINGS_KEYS } from 'src/app/data/ui-settings'
|
import { SETTINGS_KEYS } from 'src/app/data/ui-settings'
|
||||||
import { DisplayTagsPipe } from 'src/app/pipes/display-tags.pipe'
|
|
||||||
import { CorrespondentNamePipe } from 'src/app/pipes/correspondent-name.pipe'
|
import { CorrespondentNamePipe } from 'src/app/pipes/correspondent-name.pipe'
|
||||||
import { CustomDatePipe } from 'src/app/pipes/custom-date.pipe'
|
import { CustomDatePipe } from 'src/app/pipes/custom-date.pipe'
|
||||||
import { DocumentTitlePipe } from 'src/app/pipes/document-title.pipe'
|
import { DocumentTitlePipe } from 'src/app/pipes/document-title.pipe'
|
||||||
@@ -48,8 +45,6 @@ import { LoadingComponentWithPermissions } from '../../loading-component/loading
|
|||||||
TagComponent,
|
TagComponent,
|
||||||
CustomFieldDisplayComponent,
|
CustomFieldDisplayComponent,
|
||||||
AsyncPipe,
|
AsyncPipe,
|
||||||
DisplayTagsPipe,
|
|
||||||
HiddenTagsBadgeComponent,
|
|
||||||
NgOptimizedImage,
|
NgOptimizedImage,
|
||||||
UsernamePipe,
|
UsernamePipe,
|
||||||
CorrespondentNamePipe,
|
CorrespondentNamePipe,
|
||||||
@@ -95,20 +90,12 @@ export class DocumentCardSmallComponent
|
|||||||
@Output()
|
@Output()
|
||||||
clickStoragePath = new EventEmitter<number>()
|
clickStoragePath = new EventEmitter<number>()
|
||||||
|
|
||||||
private get tagLimit(): number {
|
get moreTags(): number {
|
||||||
return this.document()?.notes.length > 0 ? 6 : 7
|
const document = this.document()
|
||||||
}
|
const limit = document?.notes.length > 0 ? 6 : 7
|
||||||
|
return document?.tags.length > limit
|
||||||
/**
|
? document.tags.length - (limit - 1)
|
||||||
* The hidden tags badge only fills a slot the visible tags leave free.
|
: null
|
||||||
*/
|
|
||||||
showHiddenTags(tags: TagPartition): boolean {
|
|
||||||
return tags?.hidden.length > 0 && tags.visible.length < this.tagLimit
|
|
||||||
}
|
|
||||||
|
|
||||||
getMoreTags(tagIDs: number[]): number {
|
|
||||||
const limit = this.tagLimit
|
|
||||||
return tagIDs?.length > limit ? tagIDs.length - (limit - 1) : null
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@ViewChild('popupPreview') popupPreview: PreviewPopupComponent
|
@ViewChild('popupPreview') popupPreview: PreviewPopupComponent
|
||||||
@@ -129,9 +116,14 @@ export class DocumentCardSmallComponent
|
|||||||
return this.documentService.getDownloadUrl(this.document().id)
|
return this.documentService.getDownloadUrl(this.document().id)
|
||||||
}
|
}
|
||||||
|
|
||||||
getTagIDs(tagIDs: number[]): number[] {
|
get tagIDs() {
|
||||||
const limit = this.tagLimit
|
const document = this.document()
|
||||||
return tagIDs?.length > limit ? tagIDs.slice(0, limit - 1) : tagIDs
|
const limit = document.notes.length > 0 ? 6 : 7
|
||||||
|
if (document.tags.length > limit) {
|
||||||
|
return document.tags.slice(0, limit - 1)
|
||||||
|
} else {
|
||||||
|
return document.tags
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
mouseLeaveCard() {
|
mouseLeaveCard() {
|
||||||
|
|||||||
@@ -335,12 +335,8 @@
|
|||||||
<a routerLink="/documents/{{d.id}}" title="Edit document" i18n-title style="overflow-wrap: anywhere;">{{d.title | documentTitle}}</a>
|
<a routerLink="/documents/{{d.id}}" title="Edit document" i18n-title style="overflow-wrap: anywhere;">{{d.title | documentTitle}}</a>
|
||||||
}
|
}
|
||||||
@if (activeDisplayFields.includes(DisplayField.TAGS)) {
|
@if (activeDisplayFields.includes(DisplayField.TAGS)) {
|
||||||
@let tags = d.tags | displayTags | async;
|
@for (tagID of d.tags; track tagID) {
|
||||||
@for (tagID of tags?.visible; track tagID) {
|
<pngx-tag [tagID]="tagID" class="ms-1 fs-6" clickable="true" linkTitle="Filter by tag" i18n-linkTitle (click)="clickTag(tagID);$event.stopPropagation()"></pngx-tag>
|
||||||
<pngx-tag [tagID]="tagID" [split]="true" class="ms-1 fs-6" clickable="true" linkTitle="Filter by tag" i18n-linkTitle (click)="clickTag(tagID);$event.stopPropagation()" (parentClick)="clickTag($event)"></pngx-tag>
|
|
||||||
}
|
|
||||||
@if (tags?.hidden.length) {
|
|
||||||
<pngx-hidden-tags-badge [count]="tags.hidden.length" class="ms-1 fs-6"></pngx-hidden-tags-badge>
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
</td>
|
</td>
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import { HiddenTagsBadgeComponent } from 'src/app/components/common/hidden-tags-badge/hidden-tags-badge.component'
|
|
||||||
import { AsyncPipe, NgClass, NgTemplateOutlet } from '@angular/common'
|
import { AsyncPipe, NgClass, NgTemplateOutlet } from '@angular/common'
|
||||||
import {
|
import {
|
||||||
Component,
|
Component,
|
||||||
@@ -40,7 +39,6 @@ import {
|
|||||||
SortableDirective,
|
SortableDirective,
|
||||||
SortEvent,
|
SortEvent,
|
||||||
} from 'src/app/directives/sortable.directive'
|
} from 'src/app/directives/sortable.directive'
|
||||||
import { DisplayTagsPipe } from 'src/app/pipes/display-tags.pipe'
|
|
||||||
import { CorrespondentNamePipe } from 'src/app/pipes/correspondent-name.pipe'
|
import { CorrespondentNamePipe } from 'src/app/pipes/correspondent-name.pipe'
|
||||||
import { CustomDatePipe } from 'src/app/pipes/custom-date.pipe'
|
import { CustomDatePipe } from 'src/app/pipes/custom-date.pipe'
|
||||||
import { DocumentTitlePipe } from 'src/app/pipes/document-title.pipe'
|
import { DocumentTitlePipe } from 'src/app/pipes/document-title.pipe'
|
||||||
@@ -98,8 +96,6 @@ import { SaveViewConfigDialogComponent } from './save-view-config-dialog/save-vi
|
|||||||
StoragePathNamePipe,
|
StoragePathNamePipe,
|
||||||
BootstrapIconComponent,
|
BootstrapIconComponent,
|
||||||
AsyncPipe,
|
AsyncPipe,
|
||||||
DisplayTagsPipe,
|
|
||||||
HiddenTagsBadgeComponent,
|
|
||||||
FormsModule,
|
FormsModule,
|
||||||
ReactiveFormsModule,
|
ReactiveFormsModule,
|
||||||
NgTemplateOutlet,
|
NgTemplateOutlet,
|
||||||
|
|||||||
+1
-1
@@ -16,7 +16,7 @@
|
|||||||
</pngx-input-select>
|
</pngx-input-select>
|
||||||
<pngx-input-check i18n-title title="Show in sidebar" formControlName="showInSideBar"></pngx-input-check>
|
<pngx-input-check i18n-title title="Show in sidebar" formControlName="showInSideBar"></pngx-input-check>
|
||||||
<pngx-input-check i18n-title title="Show on dashboard" formControlName="showOnDashboard"></pngx-input-check>
|
<pngx-input-check i18n-title title="Show on dashboard" formControlName="showOnDashboard"></pngx-input-check>
|
||||||
<pngx-permissions-form [users]="users()" accordion="true" formControlName="permissions_form"></pngx-permissions-form>
|
<pngx-permissions-form accordion="true" formControlName="permissions_form"></pngx-permissions-form>
|
||||||
@if (error()?.filter_rules) {
|
@if (error()?.filter_rules) {
|
||||||
<div class="alert alert-danger" role="alert">
|
<div class="alert alert-danger" role="alert">
|
||||||
<h6 class="alert-heading" i18n>Filter rules error occurred while saving this view</h6>
|
<h6 class="alert-heading" i18n>Filter rules error occurred while saving this view</h6>
|
||||||
|
|||||||
+1
-16
@@ -3,7 +3,6 @@ import { FormsModule, ReactiveFormsModule } from '@angular/forms'
|
|||||||
import { By } from '@angular/platform-browser'
|
import { By } from '@angular/platform-browser'
|
||||||
import { NgbActiveModal, NgbModalModule } from '@ng-bootstrap/ng-bootstrap'
|
import { NgbActiveModal, NgbModalModule } from '@ng-bootstrap/ng-bootstrap'
|
||||||
import { of } from 'rxjs'
|
import { of } from 'rxjs'
|
||||||
import { User } from 'src/app/data/user'
|
|
||||||
import { GroupService } from 'src/app/services/rest/group.service'
|
import { GroupService } from 'src/app/services/rest/group.service'
|
||||||
import { UserService } from 'src/app/services/rest/user.service'
|
import { UserService } from 'src/app/services/rest/user.service'
|
||||||
import { CheckComponent } from '../../common/input/check/check.component'
|
import { CheckComponent } from '../../common/input/check/check.component'
|
||||||
@@ -15,7 +14,6 @@ import { TextComponent } from '../../common/input/text/text.component'
|
|||||||
import { SaveViewConfigDialogComponent } from './save-view-config-dialog.component'
|
import { SaveViewConfigDialogComponent } from './save-view-config-dialog.component'
|
||||||
|
|
||||||
describe('SaveViewConfigDialogComponent', () => {
|
describe('SaveViewConfigDialogComponent', () => {
|
||||||
const users = [{ id: 10, username: 'user10' }] as User[]
|
|
||||||
let component: SaveViewConfigDialogComponent
|
let component: SaveViewConfigDialogComponent
|
||||||
let fixture: ComponentFixture<SaveViewConfigDialogComponent>
|
let fixture: ComponentFixture<SaveViewConfigDialogComponent>
|
||||||
let modal: NgbActiveModal
|
let modal: NgbActiveModal
|
||||||
@@ -27,7 +25,7 @@ describe('SaveViewConfigDialogComponent', () => {
|
|||||||
{
|
{
|
||||||
provide: UserService,
|
provide: UserService,
|
||||||
useValue: {
|
useValue: {
|
||||||
listAll: () => of({ results: users }),
|
listAll: () => of({ results: [] }),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -126,19 +124,6 @@ describe('SaveViewConfigDialogComponent', () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should list users in the owner selector', () => {
|
|
||||||
fixture.debugElement
|
|
||||||
.query(By.css('button[ngbAccordionButton]'))
|
|
||||||
.nativeElement.click()
|
|
||||||
fixture.detectChanges()
|
|
||||||
|
|
||||||
const permissionsForm = fixture.debugElement.query(
|
|
||||||
By.directive(PermissionsFormComponent)
|
|
||||||
)
|
|
||||||
const ownerSelect = permissionsForm.query(By.directive(SelectComponent))
|
|
||||||
expect(ownerSelect.componentInstance.items).toEqual(users)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should support default name', () => {
|
it('should support default name', () => {
|
||||||
const saveClickedSpy = jest.spyOn(component.saveClicked, 'emit')
|
const saveClickedSpy = jest.spyOn(component.saveClicked, 'emit')
|
||||||
const modalCloseSpy = jest.spyOn(modal, 'close')
|
const modalCloseSpy = jest.spyOn(modal, 'close')
|
||||||
|
|||||||
+1
-16
@@ -6,7 +6,6 @@ import {
|
|||||||
inject,
|
inject,
|
||||||
signal,
|
signal,
|
||||||
} from '@angular/core'
|
} from '@angular/core'
|
||||||
import { toSignal } from '@angular/core/rxjs-interop'
|
|
||||||
import {
|
import {
|
||||||
FormControl,
|
FormControl,
|
||||||
FormGroup,
|
FormGroup,
|
||||||
@@ -14,14 +13,11 @@ import {
|
|||||||
ReactiveFormsModule,
|
ReactiveFormsModule,
|
||||||
} from '@angular/forms'
|
} from '@angular/forms'
|
||||||
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'
|
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'
|
||||||
import { catchError, map, of } from 'rxjs'
|
|
||||||
import {
|
import {
|
||||||
DEFAULT_SAVED_VIEW_ICON,
|
DEFAULT_SAVED_VIEW_ICON,
|
||||||
SAVED_VIEW_ICONS,
|
SAVED_VIEW_ICONS,
|
||||||
} from 'src/app/data/saved-view-icons'
|
} from 'src/app/data/saved-view-icons'
|
||||||
import { User } from 'src/app/data/user'
|
import { User } from 'src/app/data/user'
|
||||||
import { UserService } from 'src/app/services/rest/user.service'
|
|
||||||
import { ToastService } from 'src/app/services/toast.service'
|
|
||||||
import { CheckComponent } from '../../common/input/check/check.component'
|
import { CheckComponent } from '../../common/input/check/check.component'
|
||||||
import { PermissionsFormComponent } from '../../common/input/permissions/permissions-form/permissions-form.component'
|
import { PermissionsFormComponent } from '../../common/input/permissions/permissions-form/permissions-form.component'
|
||||||
import { SelectComponent } from '../../common/input/select/select.component'
|
import { SelectComponent } from '../../common/input/select/select.component'
|
||||||
@@ -42,8 +38,6 @@ import { TextComponent } from '../../common/input/text/text.component'
|
|||||||
})
|
})
|
||||||
export class SaveViewConfigDialogComponent implements OnInit {
|
export class SaveViewConfigDialogComponent implements OnInit {
|
||||||
private modal = inject(NgbActiveModal)
|
private modal = inject(NgbActiveModal)
|
||||||
private userService = inject(UserService)
|
|
||||||
private toastService = inject(ToastService)
|
|
||||||
readonly error = signal(undefined)
|
readonly error = signal(undefined)
|
||||||
readonly buttonsEnabled = signal(true)
|
readonly buttonsEnabled = signal(true)
|
||||||
readonly defaultName = signal('')
|
readonly defaultName = signal('')
|
||||||
@@ -52,16 +46,7 @@ export class SaveViewConfigDialogComponent implements OnInit {
|
|||||||
@Output()
|
@Output()
|
||||||
public saveClicked = new EventEmitter()
|
public saveClicked = new EventEmitter()
|
||||||
|
|
||||||
readonly users = toSignal(
|
users: User[]
|
||||||
this.userService.listAll().pipe(
|
|
||||||
map((result) => result.results),
|
|
||||||
catchError((error) => {
|
|
||||||
this.toastService.showError($localize`Error retrieving users`, error)
|
|
||||||
return of([])
|
|
||||||
})
|
|
||||||
),
|
|
||||||
{ initialValue: undefined as User[] }
|
|
||||||
)
|
|
||||||
readonly savedViewIcons = SAVED_VIEW_ICONS
|
readonly savedViewIcons = SAVED_VIEW_ICONS
|
||||||
|
|
||||||
setDefaultName(value: string) {
|
setDefaultName(value: string) {
|
||||||
|
|||||||
-36
@@ -1,36 +0,0 @@
|
|||||||
@if (zones.length === 0) {
|
|
||||||
<p class="text-muted" i18n>No zones yet. Drag anywhere on the sample document to create one.</p>
|
|
||||||
} @else {
|
|
||||||
<div class="list-group">
|
|
||||||
@for (zone of zones; track $index; let i = $index) {
|
|
||||||
<div class="list-group-item list-group-item-action d-flex align-items-center gap-3 position-relative">
|
|
||||||
<span class="p-2 rounded flex-shrink-0" [style.background-color]="zoneColor(i)" aria-hidden="true"></span>
|
|
||||||
<div class="flex-grow-1 text-truncate">
|
|
||||||
<button type="button" class="btn btn-link p-0 fw-semibold text-reset text-decoration-none text-truncate mw-100 stretched-link" (click)="zoneSelected.emit(i)">{{ zone.name }}</button>
|
|
||||||
@if (!hasField(zone)) {
|
|
||||||
<div class="small text-warning text-truncate">
|
|
||||||
<pngx-bs-icon name="exclamation-triangle" class="me-1" aria-hidden="true"></pngx-bs-icon><span i18n>No field selected</span>
|
|
||||||
</div>
|
|
||||||
} @else {
|
|
||||||
<div class="small text-muted text-truncate">
|
|
||||||
{{ getZoneTargetName(zone) }}
|
|
||||||
@if (isCombined(zone)) {
|
|
||||||
<pngx-bs-icon name="braces" class="ms-1" title="Combined with other zones" i18n-title></pngx-bs-icon>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
<small class="text-muted text-nowrap">
|
|
||||||
@if (zone.page === -1) {
|
|
||||||
<ng-container i18n>Last page</ng-container>
|
|
||||||
} @else {
|
|
||||||
<ng-container i18n>Page {{ zone.page ?? 1 }}</ng-container>
|
|
||||||
}
|
|
||||||
</small>
|
|
||||||
<button type="button" class="btn btn-sm btn-link text-danger position-relative z-2" (click)="zoneRemoved.emit(i)" title="Delete zone" i18n-title aria-label="Delete zone" i18n-aria-label>
|
|
||||||
<pngx-bs-icon name="trash"></pngx-bs-icon>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
-115
@@ -1,115 +0,0 @@
|
|||||||
import { ComponentFixture, TestBed } from '@angular/core/testing'
|
|
||||||
import { BootstrapIconComponent } from 'src/app/components/common/bootstrap-icon/bootstrap-icon.component'
|
|
||||||
import { CustomField } from 'src/app/data/custom-field'
|
|
||||||
import {
|
|
||||||
OcrTemplateZone,
|
|
||||||
OcrZoneTarget,
|
|
||||||
OcrZoneTransform,
|
|
||||||
} from 'src/app/data/ocr-template'
|
|
||||||
import { OcrTemplateEditorZoneListComponent } from './ocr-template-editor-zone-list.component'
|
|
||||||
|
|
||||||
function zone(overrides: Partial<OcrTemplateZone> = {}): OcrTemplateZone {
|
|
||||||
return {
|
|
||||||
name: 'Zone 1',
|
|
||||||
target: OcrZoneTarget.CustomField,
|
|
||||||
custom_field: 7,
|
|
||||||
x: 10,
|
|
||||||
y: 20,
|
|
||||||
width: 30,
|
|
||||||
height: 40,
|
|
||||||
page: 1,
|
|
||||||
ocr_language: 'eng',
|
|
||||||
transform: OcrZoneTransform.Strip,
|
|
||||||
validation_regex: '',
|
|
||||||
order: 0,
|
|
||||||
...overrides,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('OcrTemplateEditorZoneListComponent', () => {
|
|
||||||
let fixture: ComponentFixture<OcrTemplateEditorZoneListComponent>
|
|
||||||
let component: OcrTemplateEditorZoneListComponent
|
|
||||||
|
|
||||||
beforeEach(async () => {
|
|
||||||
await TestBed.configureTestingModule({
|
|
||||||
imports: [OcrTemplateEditorZoneListComponent, BootstrapIconComponent],
|
|
||||||
}).compileComponents()
|
|
||||||
|
|
||||||
fixture = TestBed.createComponent(OcrTemplateEditorZoneListComponent)
|
|
||||||
component = fixture.componentInstance
|
|
||||||
})
|
|
||||||
|
|
||||||
it('shows empty state when no zones are defined', () => {
|
|
||||||
fixture.detectChanges()
|
|
||||||
|
|
||||||
expect(fixture.nativeElement.textContent).toContain('No zones yet')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('renders zone name, target, and page', () => {
|
|
||||||
component.zones = [zone(), zone({ name: 'Zone 2', page: -1 })]
|
|
||||||
component.customFields = [{ id: 7, name: 'Invoice Number' } as CustomField]
|
|
||||||
fixture.detectChanges()
|
|
||||||
|
|
||||||
const text = fixture.nativeElement.textContent
|
|
||||||
expect(text).toContain('Zone 1')
|
|
||||||
expect(text).toContain('Invoice Number')
|
|
||||||
expect(text).toContain('Page 1')
|
|
||||||
expect(text).toContain('Last page')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('marks zones that share a field', () => {
|
|
||||||
component.zones = [
|
|
||||||
zone(),
|
|
||||||
zone({ name: 'Zone 2' }),
|
|
||||||
zone({ name: 'Zone 3', custom_field: 8 }),
|
|
||||||
]
|
|
||||||
fixture.detectChanges()
|
|
||||||
|
|
||||||
expect(component.isCombined(component.zones[0])).toBe(true)
|
|
||||||
expect(component.isCombined(component.zones[2])).toBe(false)
|
|
||||||
expect(
|
|
||||||
fixture.nativeElement.querySelectorAll(
|
|
||||||
'[title="Combined with other zones"]'
|
|
||||||
)
|
|
||||||
).toHaveLength(2)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('warns only for zones without a field and clears the warning when assigned', () => {
|
|
||||||
component.zones = [
|
|
||||||
zone({ custom_field: null }),
|
|
||||||
zone({ target: OcrZoneTarget.Title, custom_field: null }),
|
|
||||||
zone(),
|
|
||||||
]
|
|
||||||
fixture.detectChanges()
|
|
||||||
|
|
||||||
const warnings = () =>
|
|
||||||
fixture.nativeElement.querySelectorAll('.text-warning')
|
|
||||||
expect(warnings()).toHaveLength(1)
|
|
||||||
expect(warnings()[0].textContent).toContain('No field selected')
|
|
||||||
|
|
||||||
component.zones[0].custom_field = 7
|
|
||||||
fixture.componentRef.setInput('zones', [...component.zones])
|
|
||||||
fixture.detectChanges()
|
|
||||||
expect(warnings()).toHaveLength(0)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('emits select and remove events', () => {
|
|
||||||
component.zones = [zone()]
|
|
||||||
const selectSpy = jest.spyOn(component.zoneSelected, 'emit')
|
|
||||||
const removeSpy = jest.spyOn(component.zoneRemoved, 'emit')
|
|
||||||
fixture.detectChanges()
|
|
||||||
|
|
||||||
const buttons = fixture.nativeElement.querySelectorAll('button')
|
|
||||||
buttons[0].click()
|
|
||||||
buttons[1].click()
|
|
||||||
|
|
||||||
expect(selectSpy).toHaveBeenCalledWith(0)
|
|
||||||
expect(removeSpy).toHaveBeenCalledWith(0)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('does not label an unknown built-in target', () => {
|
|
||||||
expect(
|
|
||||||
component.getZoneTargetName(zone({ target: 'unknown' as OcrZoneTarget }))
|
|
||||||
).toBe('')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
-50
@@ -1,50 +0,0 @@
|
|||||||
import { Component, EventEmitter, Input, Output } from '@angular/core'
|
|
||||||
import { BootstrapIconComponent } from 'src/app/components/common/bootstrap-icon/bootstrap-icon.component'
|
|
||||||
import { CustomField } from 'src/app/data/custom-field'
|
|
||||||
import {
|
|
||||||
getZoneFieldKey,
|
|
||||||
OCR_BUILTIN_TARGETS,
|
|
||||||
OcrTemplateZone,
|
|
||||||
OcrZoneTarget,
|
|
||||||
} from 'src/app/data/ocr-template'
|
|
||||||
import { getZoneColor } from '../zone-geometry'
|
|
||||||
|
|
||||||
@Component({
|
|
||||||
selector: 'pngx-ocr-template-zone-list',
|
|
||||||
imports: [BootstrapIconComponent],
|
|
||||||
templateUrl: './ocr-template-editor-zone-list.component.html',
|
|
||||||
})
|
|
||||||
export class OcrTemplateEditorZoneListComponent {
|
|
||||||
@Input() zones: OcrTemplateZone[] = []
|
|
||||||
@Input() customFields: CustomField[] = []
|
|
||||||
|
|
||||||
@Output() public readonly zoneSelected = new EventEmitter<number>()
|
|
||||||
@Output() public readonly zoneRemoved = new EventEmitter<number>()
|
|
||||||
|
|
||||||
public readonly zoneColor = getZoneColor
|
|
||||||
|
|
||||||
hasField(zone: OcrTemplateZone): boolean {
|
|
||||||
return getZoneFieldKey(zone) !== null
|
|
||||||
}
|
|
||||||
|
|
||||||
isCombined(zone: OcrTemplateZone): boolean {
|
|
||||||
const key = getZoneFieldKey(zone)
|
|
||||||
return (
|
|
||||||
key !== null &&
|
|
||||||
this.zones.filter((z) => getZoneFieldKey(z) === key).length > 1
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
getZoneTargetName(zone: OcrTemplateZone): string {
|
|
||||||
if (zone.target === OcrZoneTarget.CustomField) {
|
|
||||||
return (
|
|
||||||
this.customFields.find((field) => field.id === zone.custom_field)
|
|
||||||
?.name ?? ''
|
|
||||||
)
|
|
||||||
}
|
|
||||||
return (
|
|
||||||
OCR_BUILTIN_TARGETS.find((target) => target.id === zone.target)?.name ??
|
|
||||||
''
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-315
@@ -1,315 +0,0 @@
|
|||||||
<div class="modal-header">
|
|
||||||
<h4 class="modal-title" id="ocr-template-editor-title">{{ dialogTitle }}</h4>
|
|
||||||
@if (template.id) {
|
|
||||||
<span class="badge bg-primary text-primary-text-contrast ms-2">ID: {{ template.id }}</span>
|
|
||||||
}
|
|
||||||
<button type="button" class="btn-close" (click)="activeModal.dismiss()" [disabled]="saving()" aria-label="Close" i18n-aria-label></button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="modal-body d-flex flex-column">
|
|
||||||
<div class="row gx-3 editor-layout flex-grow-1 flex-lg-nowrap" [attr.inert]="saving() ? '' : null" [attr.aria-busy]="saving()">
|
|
||||||
<div class="col-lg-4 mb-3 mb-lg-0 overflow-auto">
|
|
||||||
<ul ngbNav #nav="ngbNav" [(activeId)]="activeTab" class="nav-underline flex-nowrap flex-md-wrap overflow-auto">
|
|
||||||
<li ngbNavItem="template">
|
|
||||||
<a ngbNavLink i18n>Template</a>
|
|
||||||
<ng-template ngbNavContent>
|
|
||||||
<div class="row mb-3">
|
|
||||||
<div class="col-9">
|
|
||||||
<pngx-input-text [(ngModel)]="template.name" title="Template name" i18n-title></pngx-input-text>
|
|
||||||
</div>
|
|
||||||
<div class="col-3">
|
|
||||||
<pngx-input-switch [(ngModel)]="template.enabled" title="Enabled" i18n-title></pngx-input-switch>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<pngx-input-select [(ngModel)]="template.matching_algorithm" [items]="matchingAlgorithms" title="Matching algorithm" i18n-title></pngx-input-select>
|
|
||||||
@if (patternRequired) {
|
|
||||||
<pngx-input-text [(ngModel)]="template.match" title="Matching pattern" i18n-title></pngx-input-text>
|
|
||||||
<pngx-input-check [(ngModel)]="template.is_insensitive" title="Case insensitive" i18n-title></pngx-input-check>
|
|
||||||
}
|
|
||||||
|
|
||||||
<div *pngxIfOwner="object">
|
|
||||||
<hr />
|
|
||||||
<pngx-permissions-form [users]="users()" [accordion]="true" [(ngModel)]="permissionsForm"></pngx-permissions-form>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
</ng-template>
|
|
||||||
</li>
|
|
||||||
|
|
||||||
<li ngbNavItem="zones">
|
|
||||||
<a ngbNavLink><ng-container i18n>Zones</ng-container> <span class="badge bg-primary ms-2">{{ template.zones.length }}</span></a>
|
|
||||||
<ng-template ngbNavContent>
|
|
||||||
@if (selectedZone; as zone) {
|
|
||||||
<div class="d-flex align-items-center gap-2 mb-3">
|
|
||||||
<button type="button" class="btn btn-sm btn-link px-0 me-auto" (click)="deselectZone()">
|
|
||||||
<pngx-bs-icon name="arrow-left" class="me-1"></pngx-bs-icon><ng-container i18n>All zones</ng-container>
|
|
||||||
</button>
|
|
||||||
<button type="button" class="btn btn-sm btn-outline-primary" (click)="testZone()" [disabled]="!previewDocId || zoneTesting">
|
|
||||||
@if (zoneTesting) {
|
|
||||||
<span class="spinner-border spinner-border-sm me-1" aria-hidden="true"></span>
|
|
||||||
} @else {
|
|
||||||
<pngx-bs-icon name="play-fill" class="me-1"></pngx-bs-icon>
|
|
||||||
}
|
|
||||||
<ng-container i18n>Test</ng-container>
|
|
||||||
</button>
|
|
||||||
<button type="button" class="btn btn-sm btn-outline-danger" (click)="removeZone(selectedZoneIndex)" title="Delete zone" i18n-title aria-label="Delete zone" i18n-aria-label>
|
|
||||||
<pngx-bs-icon name="trash"></pngx-bs-icon>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
@if (zoneTestResult; as result) {
|
|
||||||
@if (result.error) {
|
|
||||||
<div class="alert alert-warning py-2 mb-3 small" role="alert">{{ result.error }}</div>
|
|
||||||
} @else {
|
|
||||||
<dl class="row small border rounded mx-0 py-2 mb-3">
|
|
||||||
<dt class="col-4" i18n>OCR text</dt>
|
|
||||||
<dd class="col-8">
|
|
||||||
@if (result.raw_text) {
|
|
||||||
<code>{{ result.raw_text }}</code>
|
|
||||||
} @else {
|
|
||||||
<span class="text-muted" i18n>Nothing detected</span>
|
|
||||||
}
|
|
||||||
</dd>
|
|
||||||
<dt class="col-4" i18n>Value</dt>
|
|
||||||
<dd class="col-8" [class.mb-0]="!result.regex">
|
|
||||||
@if (result.value) {
|
|
||||||
<code>{{ result.value }}</code>
|
|
||||||
} @else {
|
|
||||||
<span class="text-muted" i18n>Empty</span>
|
|
||||||
}
|
|
||||||
</dd>
|
|
||||||
@if (result.regex) {
|
|
||||||
<dt class="col-4" i18n>Validation</dt>
|
|
||||||
<dd class="col-8 mb-0">
|
|
||||||
@if (result.regex_match) {
|
|
||||||
<span class="badge bg-success" i18n>Regex matches</span>
|
|
||||||
} @else {
|
|
||||||
<span class="badge bg-danger" i18n>Regex does not match</span>
|
|
||||||
}
|
|
||||||
</dd>
|
|
||||||
}
|
|
||||||
</dl>
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
<pngx-input-text [ngModel]="zone.name" (ngModelChange)="renameZone(zone, $event)" title="Name" i18n-title></pngx-input-text>
|
|
||||||
|
|
||||||
<pngx-input-select
|
|
||||||
[items]="fieldItems()"
|
|
||||||
[ngModel]="zoneFieldValue(zone)"
|
|
||||||
(ngModelChange)="setZoneField(zone, $event)"
|
|
||||||
(createNew)="createField($event)"
|
|
||||||
title="Field"
|
|
||||||
i18n-title
|
|
||||||
placeholder="Choose a field"
|
|
||||||
i18n-placeholder
|
|
||||||
hint="Where the extracted value is written."
|
|
||||||
i18n-hint
|
|
||||||
></pngx-input-select>
|
|
||||||
|
|
||||||
@if (isFieldShared(zone)) {
|
|
||||||
<pngx-input-text
|
|
||||||
[ngModel]="getCombineFormat(zone)"
|
|
||||||
(ngModelChange)="setCombineFormat(zone, $event)"
|
|
||||||
[placeholder]="defaultCombineFormat(zone)"
|
|
||||||
title="Combined value"
|
|
||||||
i18n-title
|
|
||||||
hint="Several zones write to this field. Set the format or leave empty to join them with spaces."
|
|
||||||
i18n-hint
|
|
||||||
></pngx-input-text>
|
|
||||||
<div class="d-flex flex-wrap gap-1 mt-n2 mb-3">
|
|
||||||
@for (z of zonesForField(zone); track z) {
|
|
||||||
<button type="button" class="btn btn-sm btn-outline-secondary font-monospace" (click)="insertCombineToken(zone, z)">{{ '{' + z.name + '}' }}</button>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
|
|
||||||
<div class="row align-items-end">
|
|
||||||
<div class="col">
|
|
||||||
@if (!isLastPageZone(zone)) {
|
|
||||||
<pngx-input-number [(ngModel)]="zone.page" [showAdd]="false" title="Page" i18n-title></pngx-input-number>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
<div class="col-auto">
|
|
||||||
<pngx-input-switch [ngModel]="isLastPageZone(zone)" (ngModelChange)="setLastPageZone(zone, $event)" [horizontal]="true" title="Last page" i18n-title></pngx-input-switch>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<h6 class="border-top pt-3 mt-1 mb-3" i18n>Processing</h6>
|
|
||||||
|
|
||||||
<pngx-input-select
|
|
||||||
[items]="languageOptions"
|
|
||||||
[multiple]="true"
|
|
||||||
[ngModel]="ocrLanguageArray(zone)"
|
|
||||||
(ngModelChange)="setOcrLanguages(zone, $event)"
|
|
||||||
title="OCR language"
|
|
||||||
i18n-title
|
|
||||||
placeholder="Select languages"
|
|
||||||
i18n-placeholder
|
|
||||||
></pngx-input-select>
|
|
||||||
|
|
||||||
<pngx-input-select [items]="transformOptions" [(ngModel)]="zone.transform" title="Transform" i18n-title></pngx-input-select>
|
|
||||||
|
|
||||||
@if (zone.transform === OcrZoneTransform.Date) {
|
|
||||||
<pngx-input-text
|
|
||||||
[(ngModel)]="zone.date_format"
|
|
||||||
title="Date format"
|
|
||||||
i18n-title
|
|
||||||
placeholder="Auto-detect"
|
|
||||||
i18n-placeholder
|
|
||||||
hint="Python date codes, e.g. %d.%m.%Y. Leave empty to detect the format automatically."
|
|
||||||
i18n-hint
|
|
||||||
></pngx-input-text>
|
|
||||||
}
|
|
||||||
|
|
||||||
<pngx-input-text [(ngModel)]="zone.validation_regex" title="Validation regex" i18n-title placeholder="\d{2}\.\d{2}\.\d{4}" hint="The value must match this pattern to be applied." i18n-hint></pngx-input-text>
|
|
||||||
} @else {
|
|
||||||
<pngx-ocr-template-zone-list
|
|
||||||
[zones]="template.zones"
|
|
||||||
[customFields]="customFields()"
|
|
||||||
(zoneSelected)="selectZone($event)"
|
|
||||||
(zoneRemoved)="removeZone($event)"
|
|
||||||
></pngx-ocr-template-zone-list>
|
|
||||||
}
|
|
||||||
</ng-template>
|
|
||||||
</li>
|
|
||||||
</ul>
|
|
||||||
|
|
||||||
<div [ngbNavOutlet]="nav" class="mt-3"></div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="col-lg-8 d-flex flex-column">
|
|
||||||
<div class="d-flex flex-wrap gap-2 mb-2 flex-shrink-0">
|
|
||||||
<pngx-input-document-link
|
|
||||||
class="flex-grow-1 paperless-input-select"
|
|
||||||
[ngModel]="sampleDocumentIds"
|
|
||||||
(ngModelChange)="setSampleDocument($event)"
|
|
||||||
[minimal]="true"
|
|
||||||
[multiple]="false"
|
|
||||||
placeholder="Search for a sample document"
|
|
||||||
i18n-placeholder
|
|
||||||
></pngx-input-document-link>
|
|
||||||
@if (previewDocId) {
|
|
||||||
<div class="input-group w-auto flex-nowrap">
|
|
||||||
<input class="form-control flex-grow-0 preview-page-input" type="number" min="1" [max]="previewPageCount()" [(ngModel)]="previewPageDisplay" [disabled]="!pageLoaded()" aria-label="Page" i18n-aria-label />
|
|
||||||
@if (previewPageCount(); as pageCount) {
|
|
||||||
<span class="input-group-text" i18n>of {{ pageCount }}</span>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
<fieldset class="input-group w-auto flex-nowrap" aria-label="Zoom" i18n-aria-label>
|
|
||||||
<button type="button" class="btn btn-outline-secondary" aria-label="Zoom out" i18n-aria-label [disabled]="!pageLoaded() || zoom <= 0.5" (click)="zoomOut()"><pngx-bs-icon name="dash"></pngx-bs-icon></button>
|
|
||||||
<button type="button" class="btn btn-outline-secondary preview-zoom" title="Reset zoom" i18n-title [disabled]="!pageLoaded()" (click)="resetZoom()">{{ zoom | percent: '1.0-0' }}</button>
|
|
||||||
<button type="button" class="btn btn-outline-secondary" aria-label="Zoom in" i18n-aria-label [disabled]="!pageLoaded() || zoom >= 4" (click)="zoomIn()"><pngx-bs-icon name="plus"></pngx-bs-icon></button>
|
|
||||||
</fieldset>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
<div class="flex-grow-1 overflow-hidden">
|
|
||||||
<div class="h-100 overflow-auto border" [attr.aria-busy]="previewDocId && !pageLoaded()">
|
|
||||||
@if (pageFailed()) {
|
|
||||||
<div class="py-5 px-3 text-center" role="alert">
|
|
||||||
<pngx-bs-icon name="exclamation-triangle" width="32" height="32" class="text-warning"></pngx-bs-icon>
|
|
||||||
<p class="my-3" i18n>Could not load this page.</p>
|
|
||||||
<button type="button" class="btn btn-sm btn-outline-secondary" (click)="setSampleDocument(sampleDocumentIds)"><pngx-bs-icon name="arrow-clockwise" class="me-1"></pngx-bs-icon><span i18n>Retry</span></button>
|
|
||||||
</div>
|
|
||||||
} @else if (previewDocId) {
|
|
||||||
<div class="position-relative" [class.d-none]="!pageLoaded()" [style.width.%]="zoom * 100">
|
|
||||||
<img
|
|
||||||
#pageImage
|
|
||||||
[src]="pageImageUrl"
|
|
||||||
(load)="onImageLoad()"
|
|
||||||
(error)="onImageError()"
|
|
||||||
alt="Sample document page"
|
|
||||||
i18n-alt
|
|
||||||
class="d-block w-100"
|
|
||||||
crossorigin="use-credentials"
|
|
||||||
/>
|
|
||||||
@if (pageLoaded()) {
|
|
||||||
<svg
|
|
||||||
#zoneOverlay
|
|
||||||
class="zone-overlay position-absolute top-0 start-0 w-100 h-100"
|
|
||||||
[attr.viewBox]="overlayViewBox()"
|
|
||||||
preserveAspectRatio="none"
|
|
||||||
[style.cursor]="overlayCursor"
|
|
||||||
(pointerdown)="onOverlayPointerDown($event)"
|
|
||||||
(pointermove)="onOverlayPointerMove($event)"
|
|
||||||
(pointerup)="onOverlayPointerUp($event)"
|
|
||||||
(pointercancel)="onOverlayPointerCancel($event)"
|
|
||||||
(lostpointercapture)="onOverlayPointerCancel($event)"
|
|
||||||
aria-label="Zone overlay" i18n-aria-label
|
|
||||||
>
|
|
||||||
@for (zone of template.zones; track $index; let i = $index) {
|
|
||||||
@if (zoneDisplayRect(i); as rect) {
|
|
||||||
<g>
|
|
||||||
<rect
|
|
||||||
class="zone-rect"
|
|
||||||
[class.zone-rect-selected]="selectedZoneIndex === i"
|
|
||||||
[attr.x]="rect.x"
|
|
||||||
[attr.y]="rect.y"
|
|
||||||
[attr.width]="rect.w"
|
|
||||||
[attr.height]="rect.h"
|
|
||||||
[attr.stroke]="zoneColor(i)"
|
|
||||||
[attr.fill]="zoneColor(i)"
|
|
||||||
></rect>
|
|
||||||
<text
|
|
||||||
class="zone-label fw-semibold pe-none"
|
|
||||||
[attr.x]="rect.x + overlayUnitSize(6)"
|
|
||||||
[attr.y]="zoneLabelY(rect)"
|
|
||||||
[attr.font-size]="overlayFontSize()"
|
|
||||||
[attr.fill]="zoneColor(i)"
|
|
||||||
>{{ zoneLabel(zone, i) }}</text>
|
|
||||||
|
|
||||||
@if (selectedZoneIndex === i) {
|
|
||||||
@for (handle of resizeHandles(rect); track handle.handle) {
|
|
||||||
<rect
|
|
||||||
class="zone-resize-handle"
|
|
||||||
[attr.x]="handle.x - overlayHandleSize() / 2"
|
|
||||||
[attr.y]="handle.y - overlayHandleSize() / 2"
|
|
||||||
[attr.width]="overlayHandleSize()"
|
|
||||||
[attr.height]="overlayHandleSize()"
|
|
||||||
[attr.fill]="zoneColor(i)"
|
|
||||||
></rect>
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</g>
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@if (drawingRect(); as rect) {
|
|
||||||
<rect
|
|
||||||
class="zone-drawing-rect"
|
|
||||||
[attr.x]="rect.x"
|
|
||||||
[attr.y]="rect.y"
|
|
||||||
[attr.width]="rect.w"
|
|
||||||
[attr.height]="rect.h"
|
|
||||||
></rect>
|
|
||||||
}
|
|
||||||
</svg>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
@if (!pageLoaded()) {
|
|
||||||
<div class="p-5 d-flex justify-content-center align-items-center">
|
|
||||||
<output class="spinner-border">
|
|
||||||
<span class="visually-hidden" i18n>Loading page...</span>
|
|
||||||
</output>
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
} @else {
|
|
||||||
<div class="py-5 px-3 text-center text-muted">
|
|
||||||
<pngx-bs-icon name="file-text" width="32" height="32"></pngx-bs-icon>
|
|
||||||
<p class="mt-3 mb-0" i18n>No sample document selected.</p>
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="modal-footer">
|
|
||||||
<button type="button" class="btn btn-outline-secondary" (click)="activeModal.dismiss()" [disabled]="saving()" i18n>Cancel</button>
|
|
||||||
<button type="button" class="btn btn-primary" (click)="save()" [disabled]="saving() || !isDirty">
|
|
||||||
@if (saving()) {
|
|
||||||
<span class="spinner-border spinner-border-sm me-1" aria-hidden="true"></span>
|
|
||||||
}
|
|
||||||
<span i18n>Save</span>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
-64
@@ -1,64 +0,0 @@
|
|||||||
:host {
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
min-height: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (min-width: 992px) {
|
|
||||||
.modal-body {
|
|
||||||
overflow: hidden;
|
|
||||||
}
|
|
||||||
|
|
||||||
.editor-layout {
|
|
||||||
min-height: 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.preview-page-input {
|
|
||||||
width: 3.5rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.preview-zoom {
|
|
||||||
min-width: 4rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.zone-overlay {
|
|
||||||
touch-action: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.zone-rect,
|
|
||||||
.zone-drawing-rect {
|
|
||||||
vector-effect: non-scaling-stroke;
|
|
||||||
}
|
|
||||||
|
|
||||||
.zone-rect {
|
|
||||||
fill-opacity: 0.2;
|
|
||||||
stroke-width: 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
.zone-rect-selected {
|
|
||||||
stroke-width: 3;
|
|
||||||
}
|
|
||||||
|
|
||||||
.zone-label {
|
|
||||||
font-family: var(--bs-font-sans-serif);
|
|
||||||
paint-order: stroke;
|
|
||||||
stroke: #fff;
|
|
||||||
stroke-linejoin: round;
|
|
||||||
stroke-width: 4px;
|
|
||||||
vector-effect: non-scaling-stroke;
|
|
||||||
}
|
|
||||||
|
|
||||||
.zone-resize-handle {
|
|
||||||
stroke: #fff;
|
|
||||||
stroke-width: 1;
|
|
||||||
vector-effect: non-scaling-stroke;
|
|
||||||
}
|
|
||||||
|
|
||||||
.zone-drawing-rect {
|
|
||||||
fill: var(--bs-primary);
|
|
||||||
fill-opacity: 0.2;
|
|
||||||
stroke: var(--bs-primary);
|
|
||||||
stroke-dasharray: 5 5;
|
|
||||||
stroke-width: 2;
|
|
||||||
}
|
|
||||||
-906
@@ -1,906 +0,0 @@
|
|||||||
import { provideHttpClient, withInterceptorsFromDi } from '@angular/common/http'
|
|
||||||
import { provideHttpClientTesting } from '@angular/common/http/testing'
|
|
||||||
import { ElementRef } from '@angular/core'
|
|
||||||
import { ComponentFixture, TestBed } from '@angular/core/testing'
|
|
||||||
import { By } from '@angular/platform-browser'
|
|
||||||
import { NgbActiveModal, NgbModal } from '@ng-bootstrap/ng-bootstrap'
|
|
||||||
import { BootstrapIconComponent } from 'src/app/components/common/bootstrap-icon/bootstrap-icon.component'
|
|
||||||
import { of, Subject, throwError } from 'rxjs'
|
|
||||||
import { PermissionsFormComponent } from 'src/app/components/common/input/permissions/permissions-form/permissions-form.component'
|
|
||||||
import { CustomField, CustomFieldDataType } from 'src/app/data/custom-field'
|
|
||||||
import { Document } from 'src/app/data/document'
|
|
||||||
import {
|
|
||||||
MATCH_ANY,
|
|
||||||
MATCH_AUTO,
|
|
||||||
MATCH_LITERAL,
|
|
||||||
MATCH_NONE,
|
|
||||||
} from 'src/app/data/matching-model'
|
|
||||||
import {
|
|
||||||
OcrTemplate,
|
|
||||||
OcrTemplateZone,
|
|
||||||
OcrZoneTarget,
|
|
||||||
OcrZoneTestResult,
|
|
||||||
OcrZoneTransform,
|
|
||||||
} from 'src/app/data/ocr-template'
|
|
||||||
import { SETTINGS_KEYS } from 'src/app/data/ui-settings'
|
|
||||||
import { User } from 'src/app/data/user'
|
|
||||||
import { PermissionsService } from 'src/app/services/permissions.service'
|
|
||||||
import { CustomFieldsService } from 'src/app/services/rest/custom-fields.service'
|
|
||||||
import { DocumentService } from 'src/app/services/rest/document.service'
|
|
||||||
import { OcrTemplateService } from 'src/app/services/rest/ocr-template.service'
|
|
||||||
import { UserService } from 'src/app/services/rest/user.service'
|
|
||||||
import { SettingsService } from 'src/app/services/settings.service'
|
|
||||||
import { ToastService } from 'src/app/services/toast.service'
|
|
||||||
import { OcrTemplateEditorComponent } from './ocr-template-editor.component'
|
|
||||||
|
|
||||||
const customFields: CustomField[] = [
|
|
||||||
{ id: 1, name: 'Invoice number', data_type: CustomFieldDataType.String },
|
|
||||||
{ id: 2, name: 'Status', data_type: CustomFieldDataType.Select },
|
|
||||||
]
|
|
||||||
|
|
||||||
function zone(overrides: Partial<OcrTemplateZone> = {}): OcrTemplateZone {
|
|
||||||
return {
|
|
||||||
name: 'Invoice number',
|
|
||||||
target: OcrZoneTarget.CustomField,
|
|
||||||
custom_field: 1,
|
|
||||||
x: 100,
|
|
||||||
y: 100,
|
|
||||||
width: 200,
|
|
||||||
height: 100,
|
|
||||||
page: 1,
|
|
||||||
ocr_language: 'eng',
|
|
||||||
transform: OcrZoneTransform.Strip,
|
|
||||||
validation_regex: '',
|
|
||||||
order: 0,
|
|
||||||
...overrides,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function pointer(x: number, y: number, pointerId = 1): PointerEvent {
|
|
||||||
return Object.assign(
|
|
||||||
new MouseEvent('pointermove', { clientX: x, clientY: y, button: 0 }),
|
|
||||||
{ pointerId }
|
|
||||||
) as PointerEvent
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('OcrTemplateEditorComponent', () => {
|
|
||||||
let component: OcrTemplateEditorComponent
|
|
||||||
let fixture: ComponentFixture<OcrTemplateEditorComponent>
|
|
||||||
let documentService: DocumentService
|
|
||||||
let templateService: OcrTemplateService
|
|
||||||
let modalService: NgbModal
|
|
||||||
const activeModal = { close: jest.fn(), dismiss: jest.fn() }
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
TestBed.configureTestingModule({
|
|
||||||
imports: [BootstrapIconComponent, OcrTemplateEditorComponent],
|
|
||||||
providers: [
|
|
||||||
{ provide: NgbActiveModal, useValue: activeModal },
|
|
||||||
provideHttpClient(withInterceptorsFromDi()),
|
|
||||||
provideHttpClientTesting(),
|
|
||||||
],
|
|
||||||
})
|
|
||||||
jest
|
|
||||||
.spyOn(TestBed.inject(CustomFieldsService), 'listAll')
|
|
||||||
.mockReturnValue(of({ count: 2, all: [1, 2], results: customFields }))
|
|
||||||
jest
|
|
||||||
.spyOn(TestBed.inject(UserService), 'listAll')
|
|
||||||
.mockReturnValue(of({ count: 0, all: [], results: [] }))
|
|
||||||
TestBed.inject(PermissionsService).initialize([], { id: 1 } as User)
|
|
||||||
documentService = TestBed.inject(DocumentService)
|
|
||||||
jest
|
|
||||||
.spyOn(documentService, 'get')
|
|
||||||
.mockReturnValue(of({ id: 5, page_count: 3 }))
|
|
||||||
templateService = TestBed.inject(OcrTemplateService)
|
|
||||||
modalService = TestBed.inject(NgbModal)
|
|
||||||
activeModal.close.mockReset()
|
|
||||||
fixture = TestBed.createComponent(OcrTemplateEditorComponent)
|
|
||||||
component = fixture.componentInstance
|
|
||||||
})
|
|
||||||
|
|
||||||
function prepareOverlay() {
|
|
||||||
const image = document.createElement('img')
|
|
||||||
Object.defineProperties(image, {
|
|
||||||
naturalWidth: { value: 1000 },
|
|
||||||
naturalHeight: { value: 1000 },
|
|
||||||
clientWidth: { value: 1000 },
|
|
||||||
})
|
|
||||||
const overlay = document.createElementNS(
|
|
||||||
'http://www.w3.org/2000/svg',
|
|
||||||
'svg'
|
|
||||||
)
|
|
||||||
Object.assign(overlay, {
|
|
||||||
getScreenCTM: () => ({ inverse: () => ({}) }),
|
|
||||||
createSVGPoint: () => ({
|
|
||||||
x: 0,
|
|
||||||
y: 0,
|
|
||||||
matrixTransform() {
|
|
||||||
return { x: this.x, y: this.y }
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
setPointerCapture: jest.fn(),
|
|
||||||
hasPointerCapture: () => true,
|
|
||||||
releasePointerCapture: jest.fn(),
|
|
||||||
})
|
|
||||||
component.imageRef = new ElementRef(image)
|
|
||||||
component.overlayRef = new ElementRef(overlay)
|
|
||||||
component.pageLoaded.set(true)
|
|
||||||
}
|
|
||||||
|
|
||||||
function fieldDialog() {
|
|
||||||
const dialog = {
|
|
||||||
dialogMode: { set: jest.fn() },
|
|
||||||
object: null,
|
|
||||||
succeeded: new Subject<CustomField>(),
|
|
||||||
failed: new Subject(),
|
|
||||||
}
|
|
||||||
jest
|
|
||||||
.spyOn(modalService, 'open')
|
|
||||||
.mockReturnValue({ componentInstance: dialog } as any)
|
|
||||||
return dialog
|
|
||||||
}
|
|
||||||
|
|
||||||
it('updates screen-sized overlay units when the preview image resizes', () => {
|
|
||||||
let resize: ResizeObserverCallback
|
|
||||||
const observer = {
|
|
||||||
observe: jest.fn(),
|
|
||||||
unobserve: jest.fn(),
|
|
||||||
disconnect: jest.fn(),
|
|
||||||
}
|
|
||||||
const resizeObserver = jest
|
|
||||||
.spyOn(globalThis, 'ResizeObserver')
|
|
||||||
.mockImplementation((callback) => {
|
|
||||||
resize = callback
|
|
||||||
return observer
|
|
||||||
})
|
|
||||||
const image = document.createElement('img')
|
|
||||||
const ref = new ElementRef(image)
|
|
||||||
component.pageImage = ref
|
|
||||||
expect(observer.observe).toHaveBeenCalledWith(image)
|
|
||||||
resize([], observer)
|
|
||||||
expect(component.overlayUnitSize(8)).toBe(8)
|
|
||||||
|
|
||||||
Object.defineProperties(image, {
|
|
||||||
naturalWidth: { value: 1000 },
|
|
||||||
clientWidth: { value: 500 },
|
|
||||||
})
|
|
||||||
resize([], observer)
|
|
||||||
expect(component.overlayUnitSize(8)).toBe(16)
|
|
||||||
expect(component.overlayFontSize()).toBe(24)
|
|
||||||
|
|
||||||
component.pageImage = undefined
|
|
||||||
expect(observer.disconnect).toHaveBeenCalledTimes(1)
|
|
||||||
fixture.destroy()
|
|
||||||
expect(observer.disconnect).toHaveBeenCalledTimes(2)
|
|
||||||
resizeObserver.mockRestore()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('renders loaded image dimensions, zone labels, and selection handles', () => {
|
|
||||||
component.object = {
|
|
||||||
...component.template,
|
|
||||||
id: 3,
|
|
||||||
sample_document: 5,
|
|
||||||
zones: [zone()],
|
|
||||||
}
|
|
||||||
component.selectedZoneIndex = 0
|
|
||||||
fixture.detectChanges()
|
|
||||||
const image = fixture.nativeElement.querySelector('img')
|
|
||||||
Object.defineProperties(image, {
|
|
||||||
naturalWidth: { value: 1000 },
|
|
||||||
naturalHeight: { value: 1500 },
|
|
||||||
})
|
|
||||||
image.dispatchEvent(new Event('load'))
|
|
||||||
fixture.detectChanges()
|
|
||||||
|
|
||||||
expect(component.template).toMatchObject({
|
|
||||||
source_width: 1000,
|
|
||||||
source_height: 1500,
|
|
||||||
})
|
|
||||||
expect(
|
|
||||||
fixture.nativeElement
|
|
||||||
.querySelector('.zone-overlay')
|
|
||||||
.getAttribute('viewBox')
|
|
||||||
).toBe('0 0 1000 1500')
|
|
||||||
expect(
|
|
||||||
fixture.nativeElement.querySelector('.zone-label').textContent
|
|
||||||
).toContain('Invoice number')
|
|
||||||
expect(
|
|
||||||
fixture.nativeElement.querySelectorAll('.zone-resize-handle')
|
|
||||||
).toHaveLength(8)
|
|
||||||
expect(component.zoneLabel(zone({ name: '' }), 2)).toBe('Zone 3')
|
|
||||||
expect(component.zoneLabelY({ x: 0, y: 0, w: 100, h: 100 })).toBe(14)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('offers the supported language and transform choices', () => {
|
|
||||||
expect(component.languageOptions.map((option) => option.id)).toContain(
|
|
||||||
'eng'
|
|
||||||
)
|
|
||||||
expect(component.transformOptions.map((option) => option.id)).toEqual(
|
|
||||||
Object.values(OcrZoneTransform)
|
|
||||||
)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('clamps page navigation and supports one-based page input', () => {
|
|
||||||
component.setSampleDocument([5])
|
|
||||||
component.previewPageDisplay = 2
|
|
||||||
expect(component.previewPage).toBe(1)
|
|
||||||
expect(component.previewPageDisplay).toBe(2)
|
|
||||||
expect(component.pageImageUrl).toContain('/5/2/')
|
|
||||||
component.pageLoaded.set(true)
|
|
||||||
component.goToPage(1)
|
|
||||||
expect(component.pageLoaded()).toBe(true)
|
|
||||||
component.goToPage(Infinity)
|
|
||||||
component.goToPage(NaN)
|
|
||||||
expect(component.previewPage).toBe(1)
|
|
||||||
component.goToPage(99)
|
|
||||||
expect(component.previewPage).toBe(2)
|
|
||||||
expect(component.pageLoaded()).toBe(false)
|
|
||||||
component.goToPage(-5)
|
|
||||||
expect(component.previewPage).toBe(0)
|
|
||||||
component.previewPageCount.set(null)
|
|
||||||
component.goToPage(4.7)
|
|
||||||
expect(component.previewPage).toBe(4)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('uses the standard picker styling and shows a known page total', () => {
|
|
||||||
component.setSampleDocument([5])
|
|
||||||
fixture.detectChanges()
|
|
||||||
const picker = fixture.nativeElement.querySelector(
|
|
||||||
'pngx-input-document-link'
|
|
||||||
)
|
|
||||||
expect(picker.classList.contains('paperless-input-select')).toBe(true)
|
|
||||||
const pageInput = fixture.nativeElement.querySelector(
|
|
||||||
'input[aria-label="Page"]'
|
|
||||||
)
|
|
||||||
expect(pageInput.max).toBe('3')
|
|
||||||
expect(pageInput.parentElement.textContent.trim()).toBe('of 3')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('does not display a question mark when the page total is unknown', () => {
|
|
||||||
jest
|
|
||||||
.spyOn(documentService, 'get')
|
|
||||||
.mockReturnValueOnce(of({ id: 5, page_count: null }))
|
|
||||||
component.setSampleDocument([5])
|
|
||||||
fixture.detectChanges()
|
|
||||||
const pageInput = fixture.nativeElement.querySelector(
|
|
||||||
'input[aria-label="Page"]'
|
|
||||||
)
|
|
||||||
expect(
|
|
||||||
pageInput.parentElement.querySelector('.input-group-text')
|
|
||||||
).toBeNull()
|
|
||||||
component.pageLoaded.set(true)
|
|
||||||
component.previewPageDisplay = 2
|
|
||||||
expect(component.previewPage).toBe(1)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('limits zoom and resets it to the original size', () => {
|
|
||||||
for (let i = 0; i < 20; i++) component.zoomIn()
|
|
||||||
expect(component.zoom).toBe(4)
|
|
||||||
for (let i = 0; i < 20; i++) component.zoomOut()
|
|
||||||
expect(component.zoom).toBe(0.5)
|
|
||||||
component.resetZoom()
|
|
||||||
expect(component.zoom).toBe(1)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('moves last-page zones to the last page and can pin them to a page', () => {
|
|
||||||
component.setSampleDocument([5])
|
|
||||||
const selected = zone()
|
|
||||||
component.template.zones = [selected]
|
|
||||||
expect(component.isLastPageZone(selected)).toBe(false)
|
|
||||||
component.setLastPageZone(selected, true)
|
|
||||||
expect(selected.page).toBe(-1)
|
|
||||||
expect(component.isLastPageZone(selected)).toBe(true)
|
|
||||||
component.selectZone(0)
|
|
||||||
expect(component.previewPage).toBe(2)
|
|
||||||
component.setLastPageZone(selected, false)
|
|
||||||
expect(selected.page).toBe(3)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('ignores page-count errors from a previous sample document', () => {
|
|
||||||
const pending = new Subject<Document>()
|
|
||||||
jest
|
|
||||||
.spyOn(documentService, 'get')
|
|
||||||
.mockReturnValueOnce(pending)
|
|
||||||
.mockReturnValueOnce(of({ id: 6 }))
|
|
||||||
component.setSampleDocument([5])
|
|
||||||
component.setSampleDocument([6])
|
|
||||||
pending.error(new Error('Old document failed'))
|
|
||||||
expect(component.pageFailed()).toBe(false)
|
|
||||||
expect(component.previewPageCount()).toBeNull()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('ignores non-primary, unloaded, and saving pointer gestures', () => {
|
|
||||||
prepareOverlay()
|
|
||||||
component.onOverlayPointerDown(
|
|
||||||
new MouseEvent('pointerdown', { button: 2 }) as PointerEvent
|
|
||||||
)
|
|
||||||
expect(component.drawingRect()).toBeNull()
|
|
||||||
component.pageLoaded.set(false)
|
|
||||||
component.onOverlayPointerDown(pointer(100, 100))
|
|
||||||
expect(component.drawingRect()).toBeNull()
|
|
||||||
component.pageLoaded.set(true)
|
|
||||||
component.saving.set(true)
|
|
||||||
component.onOverlayPointerDown(pointer(100, 100))
|
|
||||||
expect(component.drawingRect()).toBeNull()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('ignores pointer events when the SVG coordinate transform is unavailable', () => {
|
|
||||||
component.onOverlayPointerDown(pointer(100, 100))
|
|
||||||
expect(component.drawingRect()).toBeNull()
|
|
||||||
prepareOverlay()
|
|
||||||
jest
|
|
||||||
.spyOn(component.overlayRef.nativeElement, 'getScreenCTM')
|
|
||||||
.mockReturnValue(null)
|
|
||||||
component.onOverlayPointerDown(pointer(100, 100))
|
|
||||||
component.onOverlayPointerMove(pointer(200, 200))
|
|
||||||
expect(component.drawingRect()).toBeNull()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('updates a drawing only for its captured pointer', () => {
|
|
||||||
prepareOverlay()
|
|
||||||
component.onOverlayPointerDown(pointer(100, 100))
|
|
||||||
component.onOverlayPointerDown(pointer(500, 500, 2))
|
|
||||||
component.onOverlayPointerMove(pointer(900, 900, 2))
|
|
||||||
expect(component.drawingRect()).toEqual({ x: 100, y: 100, w: 0, h: 0 })
|
|
||||||
component.onOverlayPointerMove(pointer(250, 200))
|
|
||||||
expect(component.drawingRect()).toEqual({ x: 100, y: 100, w: 150, h: 100 })
|
|
||||||
component.onOverlayPointerUp(pointer(250, 200))
|
|
||||||
expect(component.template.zones[0]).toMatchObject({
|
|
||||||
x: 100,
|
|
||||||
y: 100,
|
|
||||||
width: 150,
|
|
||||||
height: 100,
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
it('resizes a selected zone using its corner handle', () => {
|
|
||||||
prepareOverlay()
|
|
||||||
const selected = zone()
|
|
||||||
component.template.zones = [selected]
|
|
||||||
component.selectZone(0)
|
|
||||||
component.onOverlayPointerDown(pointer(100, 100))
|
|
||||||
component.onOverlayPointerMove(pointer(50, 75))
|
|
||||||
component.onOverlayPointerUp(pointer(60, 80))
|
|
||||||
expect(selected).toMatchObject({ x: 60, y: 80, width: 240, height: 120 })
|
|
||||||
expect(component.template.zones).toHaveLength(1)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('shows the appropriate cursor over handles, zones, and empty space', () => {
|
|
||||||
prepareOverlay()
|
|
||||||
component.template.zones = [zone()]
|
|
||||||
component.onOverlayPointerMove(pointer(150, 150))
|
|
||||||
expect(component.overlayCursor).toBe('move')
|
|
||||||
component.selectZone(0)
|
|
||||||
component.onOverlayPointerMove(pointer(100, 100))
|
|
||||||
expect(component.overlayCursor).toBe('nw-resize')
|
|
||||||
component.onOverlayPointerMove(pointer(500, 500))
|
|
||||||
expect(component.overlayCursor).toBe('crosshair')
|
|
||||||
component.template.zones[0].page = 2
|
|
||||||
component.onOverlayPointerMove(pointer(100, 100))
|
|
||||||
expect(component.zoneDisplayRect(0)).toBeNull()
|
|
||||||
expect(component.overlayCursor).toBe('crosshair')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('cancels only the captured pointer and tolerates an already-lost capture', () => {
|
|
||||||
prepareOverlay()
|
|
||||||
component.onOverlayPointerCancel(pointer(100, 100))
|
|
||||||
component.onOverlayPointerDown(pointer(100, 100))
|
|
||||||
component.onOverlayPointerCancel(pointer(150, 150, 2))
|
|
||||||
expect(component.drawingRect()).not.toBeNull()
|
|
||||||
jest
|
|
||||||
.spyOn(component.overlayRef.nativeElement, 'hasPointerCapture')
|
|
||||||
.mockReturnValue(false)
|
|
||||||
component.onOverlayPointerCancel(pointer(150, 150))
|
|
||||||
expect(component.drawingRect()).toBeNull()
|
|
||||||
expect(
|
|
||||||
component.overlayRef.nativeElement.releasePointerCapture
|
|
||||||
).not.toHaveBeenCalled()
|
|
||||||
expect(component.template.zones).toEqual([])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('preserves the selected zone when an earlier or later zone is removed', () => {
|
|
||||||
component.template.zones = [zone(), zone(), zone(), zone()]
|
|
||||||
component.selectZone(1)
|
|
||||||
const selected = component.selectedZone
|
|
||||||
component.removeZone(3)
|
|
||||||
expect(component.selectedZone).toBe(selected)
|
|
||||||
component.removeZone(0)
|
|
||||||
expect(component.selectedZoneIndex).toBe(0)
|
|
||||||
expect(component.selectedZone).toBe(selected)
|
|
||||||
component.selectZone(99)
|
|
||||||
expect(component.selectedZone).toBeNull()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('does not test zones without a selection or a sample document', () => {
|
|
||||||
const test = jest.spyOn(templateService, 'testZone')
|
|
||||||
component.testZone()
|
|
||||||
component.template.zones = [zone()]
|
|
||||||
component.selectZone(0)
|
|
||||||
component.testZone()
|
|
||||||
expect(test).not.toHaveBeenCalled()
|
|
||||||
})
|
|
||||||
|
|
||||||
it.each([
|
|
||||||
{
|
|
||||||
response: { error: { error: 'OCR unavailable' } },
|
|
||||||
message: 'OCR unavailable',
|
|
||||||
},
|
|
||||||
{ response: new Error('Network failure'), message: 'Test failed' },
|
|
||||||
])('shows zone-test errors: $message', ({ response, message }) => {
|
|
||||||
component.template.zones = [zone({ page: undefined })]
|
|
||||||
component.selectZone(0)
|
|
||||||
component.setSampleDocument([5])
|
|
||||||
jest
|
|
||||||
.spyOn(templateService, 'testZone')
|
|
||||||
.mockReturnValue(throwError(() => response))
|
|
||||||
component.testZone()
|
|
||||||
expect(component.zoneTestResult).toEqual({ error: message })
|
|
||||||
expect(component.zoneTesting).toBe(false)
|
|
||||||
expect(templateService.testZone).toHaveBeenCalledWith(
|
|
||||||
5,
|
|
||||||
expect.objectContaining({ page: 1 })
|
|
||||||
)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('switches between built-in targets, custom fields, and an unassigned field', () => {
|
|
||||||
const selected = zone()
|
|
||||||
expect(component.zoneFieldValue(selected)).toBe(1)
|
|
||||||
component.setZoneField(selected, OcrZoneTarget.Title)
|
|
||||||
expect(component.zoneFieldValue(selected)).toBe(OcrZoneTarget.Title)
|
|
||||||
expect(selected.custom_field).toBeNull()
|
|
||||||
component.setZoneField(selected, 7)
|
|
||||||
expect(selected).toMatchObject({
|
|
||||||
target: OcrZoneTarget.CustomField,
|
|
||||||
custom_field: 7,
|
|
||||||
})
|
|
||||||
component.setZoneField(selected, null)
|
|
||||||
expect(component.zoneFieldValue(selected)).toBeNull()
|
|
||||||
expect(component.zonesForField(selected)).toEqual([])
|
|
||||||
component.setCombineFormat(selected, 'Ignored')
|
|
||||||
expect(component.template.combine_formats).toEqual({})
|
|
||||||
})
|
|
||||||
|
|
||||||
it('creates combine formats when absent and leaves implicit formats alone on rename', () => {
|
|
||||||
const selected = zone({ target: OcrZoneTarget.Title, custom_field: null })
|
|
||||||
component.template.combine_formats = undefined
|
|
||||||
component.renameZone(selected, 'Renamed')
|
|
||||||
expect(selected.name).toBe('Renamed')
|
|
||||||
expect(component.getCombineFormat(selected)).toBe('')
|
|
||||||
component.setCombineFormat(selected, '{Renamed} ')
|
|
||||||
component.insertCombineToken(selected, selected)
|
|
||||||
expect(component.template.combine_formats).toEqual({
|
|
||||||
title: '{Renamed} {Renamed}',
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
it('saves templates without combine formats', () => {
|
|
||||||
component.template.combine_formats = undefined
|
|
||||||
fixture.detectChanges()
|
|
||||||
expect(component.isDirty).toBe(false)
|
|
||||||
jest
|
|
||||||
.spyOn(templateService, 'create')
|
|
||||||
.mockReturnValue(of(component.template))
|
|
||||||
component.save()
|
|
||||||
expect(component.template.combine_formats).toBeUndefined()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('does not assign unsupported custom field types and surfaces creation failures', () => {
|
|
||||||
component.template.zones = [zone({ custom_field: null })]
|
|
||||||
component.selectZone(0)
|
|
||||||
const dialog = fieldDialog()
|
|
||||||
const error = jest.spyOn(TestBed.inject(ToastService), 'showError')
|
|
||||||
component.createField('Status')
|
|
||||||
expect(dialog.object).toEqual({ name: 'Status' })
|
|
||||||
dialog.succeeded.next(customFields[1])
|
|
||||||
expect(component.selectedZone.custom_field).toBeNull()
|
|
||||||
const failure = new Error('Could not save')
|
|
||||||
dialog.failed.next(failure)
|
|
||||||
expect(error).toHaveBeenCalledWith('Error saving field.', failure)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('refreshes field choices when a field is created without a selected zone', () => {
|
|
||||||
const dialog = fieldDialog()
|
|
||||||
component.createField('Total')
|
|
||||||
dialog.succeeded.next(customFields[0])
|
|
||||||
expect(component.customFields()).toEqual(customFields)
|
|
||||||
expect(component.selectedZone).toBeNull()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should edit a copy of the template and load its sample document', () => {
|
|
||||||
const original: OcrTemplate = {
|
|
||||||
...component.template,
|
|
||||||
id: 3,
|
|
||||||
name: 'Invoices',
|
|
||||||
match: 'Northwind',
|
|
||||||
matching_algorithm: MATCH_LITERAL,
|
|
||||||
sample_document: 5,
|
|
||||||
zones: [zone()],
|
|
||||||
combine_formats: { '1': '{Invoice number}' },
|
|
||||||
}
|
|
||||||
component.object = original
|
|
||||||
fixture.detectChanges()
|
|
||||||
|
|
||||||
expect(component.dialogTitle).toEqual('Edit OCR Template')
|
|
||||||
expect(component.previewDocId).toEqual(5)
|
|
||||||
expect(component.previewPageCount()).toEqual(3)
|
|
||||||
expect(component.pageImageUrl).toContain('document-page-image/5/1/')
|
|
||||||
expect(component.template.match).toEqual('Northwind')
|
|
||||||
expect(component.isDirty).toBeFalsy()
|
|
||||||
|
|
||||||
component.template.zones[0].x = 500
|
|
||||||
component.template.combine_formats['1'] = 'Edited'
|
|
||||||
expect(original.zones[0].x).toEqual(100)
|
|
||||||
expect(original.combine_formats['1']).toEqual('{Invoice number}')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should offer every matching algorithm except automatic', () => {
|
|
||||||
expect(component.matchingAlgorithms.map((a) => a.id)).not.toContain(
|
|
||||||
MATCH_AUTO
|
|
||||||
)
|
|
||||||
expect(component.template.matching_algorithm).toEqual(MATCH_ANY)
|
|
||||||
expect(component.patternRequired).toBeTruthy()
|
|
||||||
|
|
||||||
component.template.matching_algorithm = MATCH_NONE
|
|
||||||
expect(component.patternRequired).toBeFalsy()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should initialize new template permissions from saved defaults', () => {
|
|
||||||
const defaults = {
|
|
||||||
[SETTINGS_KEYS.DEFAULT_PERMS_OWNER]: 1,
|
|
||||||
[SETTINGS_KEYS.DEFAULT_PERMS_VIEW_USERS]: [2],
|
|
||||||
[SETTINGS_KEYS.DEFAULT_PERMS_VIEW_GROUPS]: [3],
|
|
||||||
[SETTINGS_KEYS.DEFAULT_PERMS_EDIT_USERS]: [],
|
|
||||||
[SETTINGS_KEYS.DEFAULT_PERMS_EDIT_GROUPS]: [4],
|
|
||||||
}
|
|
||||||
jest
|
|
||||||
.spyOn(TestBed.inject(SettingsService), 'get')
|
|
||||||
.mockImplementation((key) => defaults[key])
|
|
||||||
fixture.detectChanges()
|
|
||||||
expect(component.permissionsForm).toEqual({
|
|
||||||
owner: 1,
|
|
||||||
set_permissions: {
|
|
||||||
view: { users: [2], groups: [3] },
|
|
||||||
change: { users: [], groups: [4] },
|
|
||||||
},
|
|
||||||
})
|
|
||||||
expect(
|
|
||||||
fixture.debugElement.query(By.directive(PermissionsFormComponent))
|
|
||||||
).toBeTruthy()
|
|
||||||
expect(component.isDirty).toBe(false)
|
|
||||||
const create = jest
|
|
||||||
.spyOn(templateService, 'create')
|
|
||||||
.mockReturnValue(of({ ...component.template, id: 3 }))
|
|
||||||
component.save()
|
|
||||||
expect(create).toHaveBeenCalledWith(
|
|
||||||
expect.objectContaining(component.permissionsForm)
|
|
||||||
)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should copy existing permissions and track changes without mutating the list item', () => {
|
|
||||||
component.object = {
|
|
||||||
...component.template,
|
|
||||||
id: 3,
|
|
||||||
owner: 1,
|
|
||||||
permissions: {
|
|
||||||
view: { users: [2], groups: [] },
|
|
||||||
change: { users: [], groups: [3] },
|
|
||||||
},
|
|
||||||
}
|
|
||||||
fixture.detectChanges()
|
|
||||||
expect(component.permissionsForm.owner).toBe(1)
|
|
||||||
expect(component.isDirty).toBe(false)
|
|
||||||
component.permissionsForm.set_permissions.view.users.push(4)
|
|
||||||
expect(component.isDirty).toBe(true)
|
|
||||||
expect(component.object.permissions.view.users).toEqual([2])
|
|
||||||
const update = jest
|
|
||||||
.spyOn(templateService, 'update')
|
|
||||||
.mockReturnValue(of(component.template))
|
|
||||||
component.save()
|
|
||||||
expect(update).toHaveBeenCalledWith(
|
|
||||||
expect.objectContaining({
|
|
||||||
owner: 1,
|
|
||||||
set_permissions: {
|
|
||||||
view: { users: [2, 4], groups: [] },
|
|
||||||
change: { users: [], groups: [3] },
|
|
||||||
},
|
|
||||||
})
|
|
||||||
)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should hide sharing controls and omit permission changes for a shared editor', () => {
|
|
||||||
component.object = {
|
|
||||||
...component.template,
|
|
||||||
id: 3,
|
|
||||||
owner: 2,
|
|
||||||
user_can_change: true,
|
|
||||||
}
|
|
||||||
fixture.detectChanges()
|
|
||||||
expect(
|
|
||||||
fixture.debugElement.query(By.directive(PermissionsFormComponent))
|
|
||||||
).toBeNull()
|
|
||||||
component.permissionsForm = {
|
|
||||||
owner: 1,
|
|
||||||
set_permissions: { view: { users: [1] } },
|
|
||||||
}
|
|
||||||
const update = jest
|
|
||||||
.spyOn(templateService, 'update')
|
|
||||||
.mockReturnValue(of(component.template))
|
|
||||||
component.save()
|
|
||||||
expect(update.mock.calls[0][0].owner).toBe(2)
|
|
||||||
expect(update.mock.calls[0][0]).not.toHaveProperty('set_permissions')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should keep only the last picked sample document', () => {
|
|
||||||
component.setSampleDocument([5, 6])
|
|
||||||
expect(component.sampleDocumentIds).toEqual([6])
|
|
||||||
|
|
||||||
component.setSampleDocument([])
|
|
||||||
expect(component.previewDocId).toBeNull()
|
|
||||||
expect(component.pageImageUrl).toBeNull()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should ignore a stale sample document response', () => {
|
|
||||||
const pending = new Subject<Document>()
|
|
||||||
jest.spyOn(documentService, 'get').mockReturnValueOnce(pending)
|
|
||||||
component.setSampleDocument([5])
|
|
||||||
component.setSampleDocument([6])
|
|
||||||
pending.next({ id: 5, page_count: 99 })
|
|
||||||
|
|
||||||
expect(component.previewPageCount()).toEqual(3)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should show a failed page and retry it', () => {
|
|
||||||
jest
|
|
||||||
.spyOn(documentService, 'get')
|
|
||||||
.mockReturnValueOnce(throwError(() => new Error('offline')))
|
|
||||||
component.setSampleDocument([5])
|
|
||||||
expect(component.pageFailed()).toBeTruthy()
|
|
||||||
|
|
||||||
component.setSampleDocument(component.sampleDocumentIds)
|
|
||||||
expect(component.pageFailed()).toBeFalsy()
|
|
||||||
|
|
||||||
component.onImageError()
|
|
||||||
expect(component.pageFailed()).toBeTruthy()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should support create and update', () => {
|
|
||||||
const createSpy = jest
|
|
||||||
.spyOn(templateService, 'create')
|
|
||||||
.mockReturnValue(of({ ...component.template, id: 3 }))
|
|
||||||
const updateSpy = jest
|
|
||||||
.spyOn(templateService, 'update')
|
|
||||||
.mockReturnValue(of(component.template))
|
|
||||||
const succeededSpy = jest.spyOn(component.succeeded, 'emit')
|
|
||||||
|
|
||||||
component.save()
|
|
||||||
expect(createSpy).toHaveBeenCalled()
|
|
||||||
expect(succeededSpy).toHaveBeenCalledWith({ ...component.template, id: 3 })
|
|
||||||
expect(activeModal.close).toHaveBeenCalled()
|
|
||||||
|
|
||||||
component.saving.set(false)
|
|
||||||
component.template.id = 3
|
|
||||||
component.save()
|
|
||||||
expect(updateSpy).toHaveBeenCalledWith(component.template)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should emit failed and allow editing again after a failed save', () => {
|
|
||||||
prepareOverlay()
|
|
||||||
component.template.zones = [zone()]
|
|
||||||
const pending = new Subject<OcrTemplate>()
|
|
||||||
jest.spyOn(templateService, 'create').mockReturnValue(pending)
|
|
||||||
const failedSpy = jest.spyOn(component.failed, 'emit')
|
|
||||||
component.onOverlayPointerDown(pointer(150, 150))
|
|
||||||
|
|
||||||
component.save()
|
|
||||||
component.save()
|
|
||||||
expect(templateService.create).toHaveBeenCalledTimes(1)
|
|
||||||
component.onOverlayPointerMove(pointer(250, 250))
|
|
||||||
component.onOverlayPointerUp(pointer(250, 250))
|
|
||||||
expect(component.template.zones[0].x).toEqual(100)
|
|
||||||
|
|
||||||
pending.error(new Error('Save failed'))
|
|
||||||
expect(failedSpy).toHaveBeenCalled()
|
|
||||||
expect(component.saving()).toBeFalsy()
|
|
||||||
component.onOverlayPointerDown(pointer(150, 150))
|
|
||||||
component.onOverlayPointerUp(pointer(250, 250))
|
|
||||||
expect(component.template.zones[0].x).toEqual(200)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should track unsaved changes', () => {
|
|
||||||
fixture.detectChanges()
|
|
||||||
expect(component.isDirty).toBeFalsy()
|
|
||||||
|
|
||||||
component.template.combine_formats = { '1': '' }
|
|
||||||
expect(component.isDirty).toBeFalsy()
|
|
||||||
|
|
||||||
component.template.name = 'Invoices'
|
|
||||||
expect(component.isDirty).toBeTruthy()
|
|
||||||
component.template.name = ''
|
|
||||||
expect(component.isDirty).toBeFalsy()
|
|
||||||
|
|
||||||
component.setSampleDocument([5])
|
|
||||||
expect(component.isDirty).toBeTruthy()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should draw a zone with no field in empty space', () => {
|
|
||||||
prepareOverlay()
|
|
||||||
component.onOverlayPointerDown(pointer(100, 100))
|
|
||||||
component.onOverlayPointerUp(pointer(1200, 250))
|
|
||||||
|
|
||||||
expect(component.template.zones[0]).toMatchObject({
|
|
||||||
x: 100,
|
|
||||||
y: 100,
|
|
||||||
width: 900,
|
|
||||||
height: 150,
|
|
||||||
custom_field: null,
|
|
||||||
})
|
|
||||||
expect(component.selectedZoneIndex).toEqual(0)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should clear the selection on a click in empty space', () => {
|
|
||||||
prepareOverlay()
|
|
||||||
component.template.zones = [zone()]
|
|
||||||
component.selectZone(0)
|
|
||||||
component.onOverlayPointerDown(pointer(600, 600))
|
|
||||||
component.onOverlayPointerUp(pointer(602, 601))
|
|
||||||
|
|
||||||
expect(component.template.zones).toHaveLength(1)
|
|
||||||
expect(component.selectedZoneIndex).toBeNull()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should move a zone when dragging on it', () => {
|
|
||||||
prepareOverlay()
|
|
||||||
component.template.zones = [zone()]
|
|
||||||
component.onOverlayPointerDown(pointer(150, 150))
|
|
||||||
component.onOverlayPointerUp(pointer(250, 200))
|
|
||||||
|
|
||||||
expect(component.template.zones).toHaveLength(1)
|
|
||||||
expect(component.template.zones[0]).toMatchObject({ x: 200, y: 150 })
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should cancel a drawing on escape and ignore other pointers', () => {
|
|
||||||
prepareOverlay()
|
|
||||||
component.onOverlayPointerDown(pointer(100, 100))
|
|
||||||
component.onOverlayPointerUp(pointer(300, 200, 2))
|
|
||||||
expect(component.drawingRect()).not.toBeNull()
|
|
||||||
|
|
||||||
component.cancelDrawing()
|
|
||||||
component.onOverlayPointerUp(pointer(300, 200))
|
|
||||||
expect(component.template.zones).toEqual([])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should open a zone in the zones tab and go back to the list', () => {
|
|
||||||
component.template.zones = [zone(), zone()]
|
|
||||||
component.selectZone(1)
|
|
||||||
expect(component.activeTab).toEqual('zones')
|
|
||||||
expect(component.selectedZone).toBe(component.template.zones[1])
|
|
||||||
|
|
||||||
component.deselectZone()
|
|
||||||
expect(component.selectedZone).toBeNull()
|
|
||||||
|
|
||||||
component.selectZone(0)
|
|
||||||
component.removeZone(0)
|
|
||||||
expect(component.template.zones).toHaveLength(1)
|
|
||||||
expect(component.selectedZone).toBeNull()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should only offer custom fields OCR can write to', () => {
|
|
||||||
fixture.detectChanges()
|
|
||||||
expect(component.fieldItems().map((item) => item.id)).toEqual([
|
|
||||||
OcrZoneTarget.Title,
|
|
||||||
OcrZoneTarget.Asn,
|
|
||||||
OcrZoneTarget.Created,
|
|
||||||
1,
|
|
||||||
])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should create a custom field and assign it to the zone', () => {
|
|
||||||
const succeeded = new Subject<CustomField>()
|
|
||||||
const dialog = {
|
|
||||||
dialogMode: { set: jest.fn() },
|
|
||||||
object: null,
|
|
||||||
succeeded,
|
|
||||||
failed: new Subject(),
|
|
||||||
}
|
|
||||||
jest
|
|
||||||
.spyOn(modalService, 'open')
|
|
||||||
.mockReturnValue({ componentInstance: dialog } as any)
|
|
||||||
component.template.zones = [zone({ custom_field: null })]
|
|
||||||
component.selectZone(0)
|
|
||||||
|
|
||||||
component.createField()
|
|
||||||
expect(dialog.object).toEqual({ name: 'Invoice number' })
|
|
||||||
succeeded.next(customFields[0])
|
|
||||||
|
|
||||||
expect(component.template.zones[0].custom_field).toEqual(1)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should build and prune combine formats', () => {
|
|
||||||
const first = zone({ name: 'First' })
|
|
||||||
const second = zone({ name: 'Second' })
|
|
||||||
const other = zone({ name: 'Other', custom_field: 2 })
|
|
||||||
component.template.zones = [first, second, other]
|
|
||||||
component.template.combine_formats = { '2': '{Other}' }
|
|
||||||
|
|
||||||
expect(component.isFieldShared(first)).toBeTruthy()
|
|
||||||
expect(component.isFieldShared(other)).toBeFalsy()
|
|
||||||
expect(component.defaultCombineFormat(first)).toEqual('{First} {Second}')
|
|
||||||
|
|
||||||
component.insertCombineToken(first, second)
|
|
||||||
component.insertCombineToken(first, first)
|
|
||||||
expect(component.getCombineFormat(second)).toEqual('{Second} {First}')
|
|
||||||
|
|
||||||
jest.spyOn(templateService, 'create').mockReturnValue(of(null))
|
|
||||||
component.save()
|
|
||||||
expect(component.template.combine_formats).toEqual({
|
|
||||||
'1': '{Second} {First}',
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should update exact tokens when a zone is renamed', () => {
|
|
||||||
const first = zone({ name: 'First [value]' })
|
|
||||||
component.template.zones = [first, zone({ name: 'Second' })]
|
|
||||||
component.template.combine_formats = {
|
|
||||||
'1': 'First [value]: {First [value]} / { First [value] } / {Second} / {First [value] extra}',
|
|
||||||
'2': '{First [value]}',
|
|
||||||
}
|
|
||||||
|
|
||||||
component.renameZone(first, '')
|
|
||||||
component.renameZone(first, 'Invoice number')
|
|
||||||
|
|
||||||
expect(first.name).toEqual('Invoice number')
|
|
||||||
expect(component.template.combine_formats).toEqual({
|
|
||||||
'1': 'First [value]: {Invoice number} / {Invoice number} / {Second} / {First [value] extra}',
|
|
||||||
'2': '{First [value]}',
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should keep the language array stable until the value changes', () => {
|
|
||||||
const selected = zone({ ocr_language: 'deu+eng' })
|
|
||||||
const languages = component.ocrLanguageArray(selected)
|
|
||||||
expect(languages).toEqual(['deu', 'eng'])
|
|
||||||
expect(component.ocrLanguageArray(selected)).toBe(languages)
|
|
||||||
|
|
||||||
component.setOcrLanguages(selected, ['fra'])
|
|
||||||
expect(selected.ocr_language).toEqual('fra')
|
|
||||||
expect(component.ocrLanguageArray(selected)).toEqual(['fra'])
|
|
||||||
|
|
||||||
component.setOcrLanguages(selected, null)
|
|
||||||
expect(component.ocrLanguageArray(selected)).toEqual([])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should hide a test result once the zone changes', () => {
|
|
||||||
const selected = zone()
|
|
||||||
component.template.zones = [selected]
|
|
||||||
component.selectZone(0)
|
|
||||||
component.setSampleDocument([5])
|
|
||||||
jest
|
|
||||||
.spyOn(templateService, 'testZone')
|
|
||||||
.mockReturnValue(of({ value: '123' }))
|
|
||||||
|
|
||||||
component.testZone()
|
|
||||||
expect(component.zoneTestResult.value).toEqual('123')
|
|
||||||
|
|
||||||
selected.transform = OcrZoneTransform.Numeric
|
|
||||||
expect(component.zoneTestResult).toBeNull()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should drop a pending test when the zone or sample document changes', () => {
|
|
||||||
const pending = new Subject<OcrZoneTestResult>()
|
|
||||||
component.template.zones = [zone(), zone()]
|
|
||||||
component.selectZone(0)
|
|
||||||
component.setSampleDocument([5])
|
|
||||||
jest.spyOn(templateService, 'testZone').mockReturnValue(pending)
|
|
||||||
|
|
||||||
component.testZone()
|
|
||||||
expect(component.zoneTesting).toBeTruthy()
|
|
||||||
component.selectZone(1)
|
|
||||||
pending.next({ value: 'Old zone' })
|
|
||||||
expect(component.zoneTestResult).toBeNull()
|
|
||||||
|
|
||||||
component.testZone()
|
|
||||||
component.setSampleDocument([])
|
|
||||||
pending.next({ value: 'Old document' })
|
|
||||||
expect(component.zoneTestResult).toBeNull()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
-963
@@ -1,963 +0,0 @@
|
|||||||
import { CommonModule } from '@angular/common'
|
|
||||||
import {
|
|
||||||
Component,
|
|
||||||
computed,
|
|
||||||
ElementRef,
|
|
||||||
EventEmitter,
|
|
||||||
HostListener,
|
|
||||||
inject,
|
|
||||||
Input,
|
|
||||||
OnDestroy,
|
|
||||||
OnInit,
|
|
||||||
Output,
|
|
||||||
signal,
|
|
||||||
ViewChild,
|
|
||||||
} from '@angular/core'
|
|
||||||
import { FormsModule } from '@angular/forms'
|
|
||||||
import {
|
|
||||||
NgbActiveModal,
|
|
||||||
NgbModal,
|
|
||||||
NgbNavModule,
|
|
||||||
} from '@ng-bootstrap/ng-bootstrap'
|
|
||||||
import { BootstrapIconComponent } from 'src/app/components/common/bootstrap-icon/bootstrap-icon.component'
|
|
||||||
import { Subject, takeUntil } from 'rxjs'
|
|
||||||
import { CustomFieldEditDialogComponent } from 'src/app/components/common/edit-dialog/custom-field-edit-dialog/custom-field-edit-dialog.component'
|
|
||||||
import { EditDialogMode } from 'src/app/components/common/edit-dialog/edit-dialog.component'
|
|
||||||
import { DocumentLinkComponent } from 'src/app/components/common/input/document-link/document-link.component'
|
|
||||||
import { CheckComponent } from 'src/app/components/common/input/check/check.component'
|
|
||||||
import { NumberComponent } from 'src/app/components/common/input/number/number.component'
|
|
||||||
import {
|
|
||||||
PermissionsFormComponent,
|
|
||||||
PermissionsFormObject,
|
|
||||||
} from 'src/app/components/common/input/permissions/permissions-form/permissions-form.component'
|
|
||||||
import { SelectComponent } from 'src/app/components/common/input/select/select.component'
|
|
||||||
import { SwitchComponent } from 'src/app/components/common/input/switch/switch.component'
|
|
||||||
import { TextComponent } from 'src/app/components/common/input/text/text.component'
|
|
||||||
import { CustomField } from 'src/app/data/custom-field'
|
|
||||||
import {
|
|
||||||
MATCH_ANY,
|
|
||||||
MATCH_AUTO,
|
|
||||||
MATCH_NONE,
|
|
||||||
MATCHING_ALGORITHMS,
|
|
||||||
} from 'src/app/data/matching-model'
|
|
||||||
import {
|
|
||||||
DEFAULT_OCR_ZONE_LANGUAGE,
|
|
||||||
getZoneFieldKey,
|
|
||||||
OCR_BUILTIN_TARGETS,
|
|
||||||
OCR_SUPPORTED_FIELD_TYPES,
|
|
||||||
OcrTemplate,
|
|
||||||
OcrTemplateZone,
|
|
||||||
OcrZoneTarget,
|
|
||||||
OcrZoneTestResult,
|
|
||||||
OcrZoneTransform,
|
|
||||||
ZoneTestRequest,
|
|
||||||
} from 'src/app/data/ocr-template'
|
|
||||||
import { SETTINGS_KEYS } from 'src/app/data/ui-settings'
|
|
||||||
import { User } from 'src/app/data/user'
|
|
||||||
import { IfOwnerDirective } from 'src/app/directives/if-owner.directive'
|
|
||||||
import { PermissionsService } from 'src/app/services/permissions.service'
|
|
||||||
import { CustomFieldsService } from 'src/app/services/rest/custom-fields.service'
|
|
||||||
import { DocumentService } from 'src/app/services/rest/document.service'
|
|
||||||
import { OcrTemplateService } from 'src/app/services/rest/ocr-template.service'
|
|
||||||
import { UserService } from 'src/app/services/rest/user.service'
|
|
||||||
import { SettingsService } from 'src/app/services/settings.service'
|
|
||||||
import { ToastService } from 'src/app/services/toast.service'
|
|
||||||
import { OcrTemplateEditorZoneListComponent } from './ocr-template-editor-zone-list/ocr-template-editor-zone-list.component'
|
|
||||||
import {
|
|
||||||
DisplayRect,
|
|
||||||
DrawingRect,
|
|
||||||
findHandleAt,
|
|
||||||
findZoneAt,
|
|
||||||
getResizeHandles,
|
|
||||||
getZoneColor,
|
|
||||||
getZoneDisplayRect,
|
|
||||||
getZonePage,
|
|
||||||
HANDLE_SIZE,
|
|
||||||
isZoneOnPage,
|
|
||||||
MIN_ZONE_SIZE,
|
|
||||||
MoveStart,
|
|
||||||
moveZone,
|
|
||||||
Point,
|
|
||||||
ResizeHandle,
|
|
||||||
resizeZone,
|
|
||||||
} from './zone-geometry'
|
|
||||||
|
|
||||||
type ActiveTab = 'template' | 'zones'
|
|
||||||
type ZoneFieldSelection = OcrZoneTarget | number | null
|
|
||||||
type OverlayInteraction =
|
|
||||||
| { kind: 'idle' }
|
|
||||||
| { kind: 'drawing'; pointerId: number; rect: DrawingRect }
|
|
||||||
| { kind: 'moving'; pointerId: number; zoneIndex: number; start: MoveStart }
|
|
||||||
| {
|
|
||||||
kind: 'resizing'
|
|
||||||
pointerId: number
|
|
||||||
zoneIndex: number
|
|
||||||
handle: ResizeHandle
|
|
||||||
}
|
|
||||||
interface ZoneTest {
|
|
||||||
zone: OcrTemplateZone
|
|
||||||
/** The sample document and zone settings the result was produced from. */
|
|
||||||
key: string
|
|
||||||
result: OcrZoneTestResult | null
|
|
||||||
}
|
|
||||||
|
|
||||||
export const ZONE_TRANSFORM_OPTIONS = [
|
|
||||||
{ id: OcrZoneTransform.None, name: $localize`None` },
|
|
||||||
{ id: OcrZoneTransform.Strip, name: $localize`Strip whitespace` },
|
|
||||||
{ id: OcrZoneTransform.Uppercase, name: $localize`Uppercase` },
|
|
||||||
{ id: OcrZoneTransform.Lowercase, name: $localize`Lowercase` },
|
|
||||||
{ id: OcrZoneTransform.Numeric, name: $localize`Numeric only` },
|
|
||||||
{
|
|
||||||
id: OcrZoneTransform.StripPunctuation,
|
|
||||||
name: $localize`Remove leading/trailing punctuation`,
|
|
||||||
},
|
|
||||||
{ id: OcrZoneTransform.Date, name: $localize`Parse date` },
|
|
||||||
{ id: OcrZoneTransform.QrCode, name: $localize`Read QR/barcode` },
|
|
||||||
]
|
|
||||||
|
|
||||||
export const ZONE_LANGUAGE_OPTIONS = [
|
|
||||||
{ id: 'eng', name: $localize`English` },
|
|
||||||
{ id: 'deu', name: $localize`German` },
|
|
||||||
{ id: 'fra', name: $localize`French` },
|
|
||||||
{ id: 'ita', name: $localize`Italian` },
|
|
||||||
{ id: 'spa', name: $localize`Spanish` },
|
|
||||||
{ id: 'por', name: $localize`Portuguese` },
|
|
||||||
{ id: 'nld', name: $localize`Dutch` },
|
|
||||||
]
|
|
||||||
|
|
||||||
const TEMPLATE_MATCHING_ALGORITHMS = MATCHING_ALGORITHMS.filter(
|
|
||||||
(algorithm) => algorithm.id !== MATCH_AUTO
|
|
||||||
)
|
|
||||||
|
|
||||||
const NO_OVERLAY_INTERACTION: OverlayInteraction = { kind: 'idle' }
|
|
||||||
const RESIZE_CURSOR: Record<ResizeHandle, string> = {
|
|
||||||
nw: 'nw-resize',
|
|
||||||
ne: 'ne-resize',
|
|
||||||
sw: 'sw-resize',
|
|
||||||
se: 'se-resize',
|
|
||||||
n: 'n-resize',
|
|
||||||
s: 's-resize',
|
|
||||||
w: 'w-resize',
|
|
||||||
e: 'e-resize',
|
|
||||||
}
|
|
||||||
|
|
||||||
@Component({
|
|
||||||
selector: 'pngx-ocr-template-editor',
|
|
||||||
imports: [
|
|
||||||
DocumentLinkComponent,
|
|
||||||
NumberComponent,
|
|
||||||
TextComponent,
|
|
||||||
CheckComponent,
|
|
||||||
SelectComponent,
|
|
||||||
SwitchComponent,
|
|
||||||
CommonModule,
|
|
||||||
FormsModule,
|
|
||||||
NgbNavModule,
|
|
||||||
BootstrapIconComponent,
|
|
||||||
OcrTemplateEditorZoneListComponent,
|
|
||||||
PermissionsFormComponent,
|
|
||||||
IfOwnerDirective,
|
|
||||||
],
|
|
||||||
templateUrl: './ocr-template-editor.component.html',
|
|
||||||
styleUrls: ['./ocr-template-editor.component.scss'],
|
|
||||||
})
|
|
||||||
export class OcrTemplateEditorComponent implements OnInit, OnDestroy {
|
|
||||||
public readonly activeModal = inject(NgbActiveModal)
|
|
||||||
private readonly templateService = inject(OcrTemplateService)
|
|
||||||
private readonly customFieldsService = inject(CustomFieldsService)
|
|
||||||
private readonly documentService = inject(DocumentService)
|
|
||||||
private readonly toastService = inject(ToastService)
|
|
||||||
private readonly modalService = inject(NgbModal)
|
|
||||||
private readonly userService = inject(UserService)
|
|
||||||
private readonly settingsService = inject(SettingsService)
|
|
||||||
private readonly permissionsService = inject(PermissionsService)
|
|
||||||
private readonly destroy$ = new Subject<void>()
|
|
||||||
private readonly cancelZoneTest$ = new Subject<void>()
|
|
||||||
|
|
||||||
@Input() object: OcrTemplate
|
|
||||||
@Output() public readonly succeeded = new EventEmitter<OcrTemplate>()
|
|
||||||
@Output() public readonly failed = new EventEmitter()
|
|
||||||
|
|
||||||
@ViewChild('zoneOverlay') overlayRef: ElementRef<SVGSVGElement>
|
|
||||||
imageRef: ElementRef<HTMLImageElement>
|
|
||||||
private previewResizeObserver: ResizeObserver | null = null
|
|
||||||
private readonly overlayScale = signal(1)
|
|
||||||
|
|
||||||
@ViewChild('pageImage')
|
|
||||||
set pageImage(ref: ElementRef<HTMLImageElement> | undefined) {
|
|
||||||
this.previewResizeObserver?.disconnect()
|
|
||||||
this.imageRef = ref
|
|
||||||
if (!ref) return
|
|
||||||
this.previewResizeObserver = new ResizeObserver(() => {
|
|
||||||
const image = ref.nativeElement
|
|
||||||
if (image.naturalWidth && image.clientWidth) {
|
|
||||||
this.overlayScale.set(image.naturalWidth / image.clientWidth)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
this.previewResizeObserver.observe(ref.nativeElement)
|
|
||||||
}
|
|
||||||
|
|
||||||
template: OcrTemplate = {
|
|
||||||
id: null,
|
|
||||||
name: '',
|
|
||||||
match: '',
|
|
||||||
matching_algorithm: MATCH_ANY,
|
|
||||||
is_insensitive: true,
|
|
||||||
sample_document: null,
|
|
||||||
source_width: 0,
|
|
||||||
source_height: 0,
|
|
||||||
enabled: true,
|
|
||||||
combine_formats: {},
|
|
||||||
zones: [],
|
|
||||||
}
|
|
||||||
|
|
||||||
public readonly customFields = signal<CustomField[]>([])
|
|
||||||
public readonly fieldItems = computed<
|
|
||||||
{ id: ZoneFieldSelection; name: string }[]
|
|
||||||
>(() => [
|
|
||||||
...OCR_BUILTIN_TARGETS,
|
|
||||||
...this.customFields()
|
|
||||||
.filter((field) => OCR_SUPPORTED_FIELD_TYPES.includes(field.data_type))
|
|
||||||
.map((field) => ({ id: field.id, name: field.name })),
|
|
||||||
])
|
|
||||||
public readonly users = signal<User[]>([])
|
|
||||||
permissionsForm: PermissionsFormObject = {}
|
|
||||||
public readonly OcrZoneTransform = OcrZoneTransform
|
|
||||||
public readonly saving = signal(false)
|
|
||||||
|
|
||||||
/** Bound to the document picker, which works with id arrays. */
|
|
||||||
sampleDocumentIds: number[] = []
|
|
||||||
previewPage = 0
|
|
||||||
public readonly previewPageCount = signal<number | null>(null)
|
|
||||||
public readonly pageLoaded = signal(false)
|
|
||||||
public readonly pageFailed = signal(false)
|
|
||||||
zoom = 1
|
|
||||||
|
|
||||||
get previewDocId(): number | null {
|
|
||||||
return this.sampleDocumentIds[0] ?? null
|
|
||||||
}
|
|
||||||
|
|
||||||
get pageImageUrl(): string | null {
|
|
||||||
return this.previewDocId
|
|
||||||
? this.templateService.getPageImageUrl(
|
|
||||||
this.previewDocId,
|
|
||||||
this.previewPage + 1
|
|
||||||
)
|
|
||||||
: null
|
|
||||||
}
|
|
||||||
|
|
||||||
get transformOptions() {
|
|
||||||
return ZONE_TRANSFORM_OPTIONS
|
|
||||||
}
|
|
||||||
|
|
||||||
get languageOptions() {
|
|
||||||
return ZONE_LANGUAGE_OPTIONS
|
|
||||||
}
|
|
||||||
|
|
||||||
get matchingAlgorithms() {
|
|
||||||
return TEMPLATE_MATCHING_ALGORITHMS
|
|
||||||
}
|
|
||||||
|
|
||||||
get patternRequired(): boolean {
|
|
||||||
return (
|
|
||||||
this.template.matching_algorithm !== MATCH_AUTO &&
|
|
||||||
this.template.matching_algorithm !== MATCH_NONE
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
public get previewPageDisplay(): number {
|
|
||||||
return this.previewPage + 1
|
|
||||||
}
|
|
||||||
|
|
||||||
public set previewPageDisplay(value: number) {
|
|
||||||
this.goToPage(value - 1)
|
|
||||||
}
|
|
||||||
|
|
||||||
activeTab: ActiveTab = 'template'
|
|
||||||
|
|
||||||
selectedZoneIndex: number | null = null
|
|
||||||
private overlayInteraction: OverlayInteraction = NO_OVERLAY_INTERACTION
|
|
||||||
overlayCursor = 'crosshair'
|
|
||||||
|
|
||||||
private readonly zoneTest = signal<ZoneTest | null>(null)
|
|
||||||
|
|
||||||
get zoneTestResult(): OcrZoneTestResult | null {
|
|
||||||
return this.isCurrentZoneTest() ? this.zoneTest().result : null
|
|
||||||
}
|
|
||||||
|
|
||||||
get zoneTesting(): boolean {
|
|
||||||
return this.isCurrentZoneTest() && this.zoneTest().result === null
|
|
||||||
}
|
|
||||||
|
|
||||||
get selectedZone(): OcrTemplateZone | null {
|
|
||||||
return this.selectedZoneIndex !== null
|
|
||||||
? (this.template.zones[this.selectedZoneIndex] ?? null)
|
|
||||||
: null
|
|
||||||
}
|
|
||||||
|
|
||||||
private initialState = ''
|
|
||||||
|
|
||||||
get isDirty(): boolean {
|
|
||||||
return this.editorState() !== this.initialState
|
|
||||||
}
|
|
||||||
|
|
||||||
private editorState(): string {
|
|
||||||
const formats = Object.entries(this.template.combine_formats ?? {}).filter(
|
|
||||||
([, format]) => format
|
|
||||||
)
|
|
||||||
return JSON.stringify({
|
|
||||||
...this.template,
|
|
||||||
combine_formats: Object.fromEntries(formats),
|
|
||||||
sample_document: this.previewDocId ?? null,
|
|
||||||
permissions_form: this.permissionsForm,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
get dialogTitle(): string {
|
|
||||||
return this.template.id
|
|
||||||
? $localize`Edit OCR Template`
|
|
||||||
: $localize`New OCR Template`
|
|
||||||
}
|
|
||||||
|
|
||||||
ngOnInit() {
|
|
||||||
this.userService
|
|
||||||
.listAll()
|
|
||||||
.pipe(takeUntil(this.destroy$))
|
|
||||||
.subscribe((r) => this.users.set(r.results))
|
|
||||||
this.customFieldsService
|
|
||||||
.listAll()
|
|
||||||
.pipe(takeUntil(this.destroy$))
|
|
||||||
.subscribe((r) => {
|
|
||||||
this.customFields.set(r.results)
|
|
||||||
})
|
|
||||||
|
|
||||||
if (this.object) {
|
|
||||||
this.template = {
|
|
||||||
...this.object,
|
|
||||||
zones: this.object.zones.map((zone) => ({ ...zone })),
|
|
||||||
combine_formats: { ...this.object.combine_formats },
|
|
||||||
}
|
|
||||||
if (this.template.sample_document) {
|
|
||||||
this.setSampleDocument([this.template.sample_document])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const permissions = this.object?.permissions
|
|
||||||
this.permissionsForm = this.object
|
|
||||||
? {
|
|
||||||
owner: this.object.owner,
|
|
||||||
set_permissions: {
|
|
||||||
view: {
|
|
||||||
users: [...(permissions?.view.users ?? [])],
|
|
||||||
groups: [...(permissions?.view.groups ?? [])],
|
|
||||||
},
|
|
||||||
change: {
|
|
||||||
users: [...(permissions?.change.users ?? [])],
|
|
||||||
groups: [...(permissions?.change.groups ?? [])],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
: {
|
|
||||||
owner: this.settingsService.get(SETTINGS_KEYS.DEFAULT_PERMS_OWNER),
|
|
||||||
set_permissions: {
|
|
||||||
view: {
|
|
||||||
users: this.settingsService.get(
|
|
||||||
SETTINGS_KEYS.DEFAULT_PERMS_VIEW_USERS
|
|
||||||
),
|
|
||||||
groups: this.settingsService.get(
|
|
||||||
SETTINGS_KEYS.DEFAULT_PERMS_VIEW_GROUPS
|
|
||||||
),
|
|
||||||
},
|
|
||||||
change: {
|
|
||||||
users: this.settingsService.get(
|
|
||||||
SETTINGS_KEYS.DEFAULT_PERMS_EDIT_USERS
|
|
||||||
),
|
|
||||||
groups: this.settingsService.get(
|
|
||||||
SETTINGS_KEYS.DEFAULT_PERMS_EDIT_GROUPS
|
|
||||||
),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
this.initialState = this.editorState()
|
|
||||||
}
|
|
||||||
|
|
||||||
setSampleDocument(ids: number[]) {
|
|
||||||
const id = ids.at(-1)
|
|
||||||
this.sampleDocumentIds = id ? [id] : []
|
|
||||||
this.previewPage = 0
|
|
||||||
this.previewPageCount.set(null)
|
|
||||||
this.resetPage()
|
|
||||||
if (!id) return
|
|
||||||
this.documentService
|
|
||||||
.get(id)
|
|
||||||
.pipe(takeUntil(this.destroy$))
|
|
||||||
.subscribe({
|
|
||||||
next: (doc) => {
|
|
||||||
if (this.previewDocId !== id) return
|
|
||||||
this.previewPageCount.set(doc.page_count ?? null)
|
|
||||||
},
|
|
||||||
error: () => {
|
|
||||||
if (this.previewDocId === id) this.pageFailed.set(true)
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
private resetPage() {
|
|
||||||
this.stopOverlayInteraction()
|
|
||||||
this.clearZoneTest()
|
|
||||||
this.pageLoaded.set(false)
|
|
||||||
this.pageFailed.set(false)
|
|
||||||
}
|
|
||||||
|
|
||||||
goToPage(page: number) {
|
|
||||||
if (!Number.isFinite(page)) return
|
|
||||||
const pageCount = this.previewPageCount()
|
|
||||||
const max = pageCount ? pageCount - 1 : page
|
|
||||||
const clamped = Math.max(0, Math.min(Math.trunc(page), max))
|
|
||||||
if (clamped === this.previewPage) return
|
|
||||||
this.previewPage = clamped
|
|
||||||
this.resetPage()
|
|
||||||
}
|
|
||||||
|
|
||||||
zoomIn() {
|
|
||||||
this.zoom = Math.min(4, Math.round((this.zoom + 0.25) * 100) / 100)
|
|
||||||
}
|
|
||||||
|
|
||||||
zoomOut() {
|
|
||||||
this.zoom = Math.max(0.5, Math.round((this.zoom - 0.25) * 100) / 100)
|
|
||||||
}
|
|
||||||
|
|
||||||
resetZoom() {
|
|
||||||
this.zoom = 1
|
|
||||||
}
|
|
||||||
|
|
||||||
zonePage(zone: OcrTemplateZone): number {
|
|
||||||
return getZonePage(zone, this.previewPage, this.previewPageCount())
|
|
||||||
}
|
|
||||||
|
|
||||||
isLastPageZone(zone: OcrTemplateZone): boolean {
|
|
||||||
return zone.page === -1
|
|
||||||
}
|
|
||||||
|
|
||||||
setLastPageZone(zone: OcrTemplateZone, lastPage: boolean) {
|
|
||||||
zone.page = lastPage ? -1 : this.previewPage + 1
|
|
||||||
}
|
|
||||||
|
|
||||||
private isOnCurrentPage(zone: OcrTemplateZone): boolean {
|
|
||||||
return isZoneOnPage(zone, this.previewPage, this.previewPageCount())
|
|
||||||
}
|
|
||||||
|
|
||||||
onImageLoad() {
|
|
||||||
this.pageLoaded.set(true)
|
|
||||||
const img = this.imageRef.nativeElement
|
|
||||||
this.template.source_width = img.naturalWidth
|
|
||||||
this.template.source_height = img.naturalHeight
|
|
||||||
}
|
|
||||||
|
|
||||||
onImageError() {
|
|
||||||
this.stopOverlayInteraction()
|
|
||||||
this.pageFailed.set(true)
|
|
||||||
}
|
|
||||||
|
|
||||||
@HostListener('document:keydown.escape')
|
|
||||||
cancelDrawing() {
|
|
||||||
this.stopOverlayInteraction()
|
|
||||||
}
|
|
||||||
|
|
||||||
onOverlayPointerDown(event: PointerEvent) {
|
|
||||||
if (this.saving()) return
|
|
||||||
if (event.button !== 0 || this.overlayInteraction.kind !== 'idle') return
|
|
||||||
const point = this.svgPointFromEvent(event)
|
|
||||||
if (!this.pageLoaded() || !point) return
|
|
||||||
event.preventDefault()
|
|
||||||
|
|
||||||
if (this.selectedZoneIndex !== null) {
|
|
||||||
const handle = this.handleAt(point, this.selectedZoneIndex)
|
|
||||||
if (handle) {
|
|
||||||
this.overlayInteraction = {
|
|
||||||
kind: 'resizing',
|
|
||||||
pointerId: event.pointerId,
|
|
||||||
zoneIndex: this.selectedZoneIndex,
|
|
||||||
handle,
|
|
||||||
}
|
|
||||||
this.overlayRef.nativeElement.setPointerCapture(event.pointerId)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const clickedIdx = this.zoneIndexAt(point)
|
|
||||||
if (clickedIdx !== null) {
|
|
||||||
this.selectZone(clickedIdx)
|
|
||||||
const zone = this.template.zones[clickedIdx]
|
|
||||||
this.overlayInteraction = {
|
|
||||||
kind: 'moving',
|
|
||||||
pointerId: event.pointerId,
|
|
||||||
zoneIndex: clickedIdx,
|
|
||||||
start: {
|
|
||||||
mouseX: point.x,
|
|
||||||
mouseY: point.y,
|
|
||||||
zoneX: zone.x,
|
|
||||||
zoneY: zone.y,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
this.overlayRef.nativeElement.setPointerCapture(event.pointerId)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Empty space: start drawing a new zone. A click without a drag just clears
|
|
||||||
// the selection (see onOverlayPointerUp).
|
|
||||||
this.clearZoneTest()
|
|
||||||
this.selectedZoneIndex = null
|
|
||||||
this.overlayInteraction = {
|
|
||||||
kind: 'drawing',
|
|
||||||
pointerId: event.pointerId,
|
|
||||||
rect: {
|
|
||||||
startX: point.x,
|
|
||||||
startY: point.y,
|
|
||||||
endX: point.x,
|
|
||||||
endY: point.y,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
this.overlayRef.nativeElement.setPointerCapture(event.pointerId)
|
|
||||||
}
|
|
||||||
|
|
||||||
onOverlayPointerMove(event: PointerEvent) {
|
|
||||||
if (
|
|
||||||
this.overlayInteraction.kind !== 'idle' &&
|
|
||||||
this.overlayInteraction.pointerId !== event.pointerId
|
|
||||||
)
|
|
||||||
return
|
|
||||||
const point = this.svgPointFromEvent(event)
|
|
||||||
if (!point) return
|
|
||||||
|
|
||||||
if (this.overlayInteraction.kind === 'resizing') {
|
|
||||||
resizeZone(
|
|
||||||
this.template.zones[this.overlayInteraction.zoneIndex],
|
|
||||||
this.overlayInteraction.handle,
|
|
||||||
point,
|
|
||||||
this.imageNaturalSize()
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this.overlayInteraction.kind === 'moving') {
|
|
||||||
moveZone(
|
|
||||||
this.template.zones[this.overlayInteraction.zoneIndex],
|
|
||||||
point,
|
|
||||||
this.overlayInteraction.start,
|
|
||||||
this.imageNaturalSize()
|
|
||||||
)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this.overlayInteraction.kind === 'drawing') {
|
|
||||||
this.overlayInteraction.rect.endX = point.x
|
|
||||||
this.overlayInteraction.rect.endY = point.y
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
this.updateOverlayCursor(point)
|
|
||||||
}
|
|
||||||
|
|
||||||
private updateOverlayCursor(point: Point) {
|
|
||||||
if (this.selectedZoneIndex !== null) {
|
|
||||||
const handle = this.handleAt(point, this.selectedZoneIndex)
|
|
||||||
if (handle) {
|
|
||||||
this.overlayCursor = RESIZE_CURSOR[handle]
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
this.overlayCursor = this.zoneIndexAt(point) !== null ? 'move' : 'crosshair'
|
|
||||||
}
|
|
||||||
|
|
||||||
onOverlayPointerUp(event: PointerEvent) {
|
|
||||||
if (this.overlayInteraction.kind === 'idle') return
|
|
||||||
if (this.overlayInteraction.pointerId !== event.pointerId) return
|
|
||||||
this.onOverlayPointerMove(event)
|
|
||||||
const interaction = this.overlayInteraction
|
|
||||||
this.stopOverlayInteraction()
|
|
||||||
if (interaction.kind !== 'drawing') return
|
|
||||||
|
|
||||||
const rect = this.sourceRectFromDrawing(interaction.rect)
|
|
||||||
|
|
||||||
// Ignore tiny accidental clicks.
|
|
||||||
if (rect.w < MIN_ZONE_SIZE || rect.h < MIN_ZONE_SIZE) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
this.template.zones.push(this.createZoneFromRect(rect))
|
|
||||||
this.selectZone(this.template.zones.length - 1)
|
|
||||||
}
|
|
||||||
|
|
||||||
private createZoneFromRect(rect: DisplayRect): OcrTemplateZone {
|
|
||||||
const imageSize = this.imageNaturalSize()
|
|
||||||
return {
|
|
||||||
name: `Zone ${this.template.zones.length + 1}`,
|
|
||||||
target: OcrZoneTarget.CustomField,
|
|
||||||
custom_field: null,
|
|
||||||
x: rect.x,
|
|
||||||
y: rect.y,
|
|
||||||
width: rect.w,
|
|
||||||
height: rect.h,
|
|
||||||
page: this.previewPageDisplay,
|
|
||||||
ocr_language: DEFAULT_OCR_ZONE_LANGUAGE,
|
|
||||||
transform: OcrZoneTransform.Strip,
|
|
||||||
date_format: '',
|
|
||||||
validation_regex: '',
|
|
||||||
order: this.template.zones.length,
|
|
||||||
zone_source_width: imageSize.width,
|
|
||||||
zone_source_height: imageSize.height,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
onOverlayPointerCancel(event: PointerEvent) {
|
|
||||||
if (this.overlayInteraction.kind === 'idle') return
|
|
||||||
if (this.overlayInteraction.pointerId !== event.pointerId) return
|
|
||||||
this.stopOverlayInteraction()
|
|
||||||
}
|
|
||||||
|
|
||||||
private stopOverlayInteraction() {
|
|
||||||
const interaction = this.overlayInteraction
|
|
||||||
this.overlayInteraction = NO_OVERLAY_INTERACTION
|
|
||||||
this.overlayCursor = 'crosshair'
|
|
||||||
const overlay = this.overlayRef?.nativeElement
|
|
||||||
if (
|
|
||||||
interaction.kind !== 'idle' &&
|
|
||||||
overlay?.hasPointerCapture(interaction.pointerId)
|
|
||||||
) {
|
|
||||||
overlay.releasePointerCapture(interaction.pointerId)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
drawingRect(): DisplayRect | null {
|
|
||||||
return this.overlayInteraction.kind === 'drawing'
|
|
||||||
? this.displayRectFromDrawing(this.overlayInteraction.rect)
|
|
||||||
: null
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The zone's rectangle on the overlay, or null if it's on another page. */
|
|
||||||
zoneDisplayRect(zoneIndex: number): DisplayRect | null {
|
|
||||||
const zone = this.template.zones[zoneIndex]
|
|
||||||
if (!this.isOnCurrentPage(zone)) return null
|
|
||||||
return getZoneDisplayRect(zone, this.imageNaturalSize())
|
|
||||||
}
|
|
||||||
|
|
||||||
private handleAt(point: Point, zoneIndex: number): ResizeHandle | null {
|
|
||||||
const rect = this.zoneDisplayRect(zoneIndex)
|
|
||||||
return rect ? findHandleAt(point, rect, this.overlayHandleSize()) : null
|
|
||||||
}
|
|
||||||
|
|
||||||
private zoneIndexAt(point: Point): number | null {
|
|
||||||
return findZoneAt(
|
|
||||||
point,
|
|
||||||
this.template.zones,
|
|
||||||
this.previewPage,
|
|
||||||
this.previewPageCount(),
|
|
||||||
this.imageNaturalSize()
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
overlayViewBox(): string {
|
|
||||||
const imageSize = this.imageNaturalSize()
|
|
||||||
return `0 0 ${imageSize.width} ${imageSize.height}`
|
|
||||||
}
|
|
||||||
|
|
||||||
public readonly zoneColor = getZoneColor
|
|
||||||
|
|
||||||
zoneLabel(zone: OcrTemplateZone, index: number): string {
|
|
||||||
return zone.name || `Zone ${index + 1}`
|
|
||||||
}
|
|
||||||
|
|
||||||
zoneLabelY(rect: DisplayRect): number {
|
|
||||||
return Math.max(this.overlayUnitSize(14), rect.y - this.overlayUnitSize(4))
|
|
||||||
}
|
|
||||||
|
|
||||||
public readonly resizeHandles = getResizeHandles
|
|
||||||
|
|
||||||
overlayHandleSize(): number {
|
|
||||||
return this.overlayUnitSize(HANDLE_SIZE)
|
|
||||||
}
|
|
||||||
|
|
||||||
overlayFontSize(): number {
|
|
||||||
return this.overlayUnitSize(12)
|
|
||||||
}
|
|
||||||
|
|
||||||
overlayUnitSize(screenPixels: number): number {
|
|
||||||
return screenPixels * this.overlayScale()
|
|
||||||
}
|
|
||||||
|
|
||||||
private svgPointFromEvent(event: MouseEvent): Point | null {
|
|
||||||
const svg = this.overlayRef?.nativeElement
|
|
||||||
const matrix = svg?.getScreenCTM()
|
|
||||||
if (!svg || !matrix) return null
|
|
||||||
|
|
||||||
const point = svg.createSVGPoint()
|
|
||||||
point.x = event.clientX
|
|
||||||
point.y = event.clientY
|
|
||||||
|
|
||||||
const svgPoint = point.matrixTransform(matrix.inverse())
|
|
||||||
const size = this.imageNaturalSize()
|
|
||||||
return {
|
|
||||||
x: Math.max(0, Math.min(svgPoint.x, size.width)),
|
|
||||||
y: Math.max(0, Math.min(svgPoint.y, size.height)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private displayRectFromDrawing(rect: DrawingRect): DisplayRect {
|
|
||||||
return {
|
|
||||||
x: Math.min(rect.startX, rect.endX),
|
|
||||||
y: Math.min(rect.startY, rect.endY),
|
|
||||||
w: Math.abs(rect.endX - rect.startX),
|
|
||||||
h: Math.abs(rect.endY - rect.startY),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private sourceRectFromDrawing(rect: DrawingRect): DisplayRect {
|
|
||||||
const displayRect = this.displayRectFromDrawing(rect)
|
|
||||||
return {
|
|
||||||
x: Math.round(displayRect.x),
|
|
||||||
y: Math.round(displayRect.y),
|
|
||||||
w: Math.round(displayRect.w),
|
|
||||||
h: Math.round(displayRect.h),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private imageNaturalSize() {
|
|
||||||
const img = this.imageRef.nativeElement
|
|
||||||
return { width: img.naturalWidth, height: img.naturalHeight }
|
|
||||||
}
|
|
||||||
|
|
||||||
removeZone(index: number) {
|
|
||||||
this.stopOverlayInteraction()
|
|
||||||
this.clearZoneTest()
|
|
||||||
this.template.zones.splice(index, 1)
|
|
||||||
if (this.selectedZoneIndex === index) {
|
|
||||||
this.selectedZoneIndex = null
|
|
||||||
} else if (this.selectedZoneIndex > index) {
|
|
||||||
this.selectedZoneIndex--
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
selectZone(index: number) {
|
|
||||||
this.selectedZoneIndex = index
|
|
||||||
this.activeTab = 'zones'
|
|
||||||
this.clearZoneTest()
|
|
||||||
const zone = this.template.zones[index]
|
|
||||||
if (zone) {
|
|
||||||
this.goToPage(this.zonePage(zone) - 1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
deselectZone() {
|
|
||||||
this.selectedZoneIndex = null
|
|
||||||
this.clearZoneTest()
|
|
||||||
}
|
|
||||||
|
|
||||||
testZone() {
|
|
||||||
const zone = this.selectedZone
|
|
||||||
if (!zone || !this.previewDocId) return
|
|
||||||
this.clearZoneTest()
|
|
||||||
const test: ZoneTest = { zone, key: this.zoneTestKey(zone), result: null }
|
|
||||||
this.zoneTest.set(test)
|
|
||||||
this.templateService
|
|
||||||
.testZone(this.previewDocId, this.zoneTestRequest(zone))
|
|
||||||
.pipe(takeUntil(this.destroy$), takeUntil(this.cancelZoneTest$))
|
|
||||||
.subscribe({
|
|
||||||
next: (res) => this.zoneTest.set({ ...test, result: res }),
|
|
||||||
error: (err) =>
|
|
||||||
this.zoneTest.set({
|
|
||||||
...test,
|
|
||||||
result: { error: err.error?.error || $localize`Test failed` },
|
|
||||||
}),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
private clearZoneTest() {
|
|
||||||
this.cancelZoneTest$.next()
|
|
||||||
this.zoneTest.set(null)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A result is stale once its zone, settings or sample document change. */
|
|
||||||
private isCurrentZoneTest(): boolean {
|
|
||||||
const test = this.zoneTest()
|
|
||||||
return (
|
|
||||||
test?.zone === this.selectedZone &&
|
|
||||||
test.key === this.zoneTestKey(test.zone)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
private zoneTestKey(zone: OcrTemplateZone): string {
|
|
||||||
return JSON.stringify([this.previewDocId, this.zoneTestRequest(zone)])
|
|
||||||
}
|
|
||||||
|
|
||||||
private zoneTestRequest(zone: OcrTemplateZone): ZoneTestRequest {
|
|
||||||
return {
|
|
||||||
name: zone.name,
|
|
||||||
x: zone.x,
|
|
||||||
y: zone.y,
|
|
||||||
width: zone.width,
|
|
||||||
height: zone.height,
|
|
||||||
page: zone.page ?? 1,
|
|
||||||
ocr_language: zone.ocr_language,
|
|
||||||
transform: zone.transform,
|
|
||||||
date_format: zone.date_format,
|
|
||||||
validation_regex: zone.validation_regex,
|
|
||||||
zone_source_width: zone.zone_source_width,
|
|
||||||
zone_source_height: zone.zone_source_height,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
save() {
|
|
||||||
if (this.saving()) return
|
|
||||||
this.stopOverlayInteraction()
|
|
||||||
this.saving.set(true)
|
|
||||||
this.pruneCombineFormats()
|
|
||||||
this.template.sample_document = this.previewDocId
|
|
||||||
const payload = this.permissionsService.currentUserOwnsObject(this.object)
|
|
||||||
? { ...this.template, ...this.permissionsForm }
|
|
||||||
: this.template
|
|
||||||
const obs = this.template.id
|
|
||||||
? this.templateService.update(payload)
|
|
||||||
: this.templateService.create(payload)
|
|
||||||
|
|
||||||
obs.pipe(takeUntil(this.destroy$)).subscribe({
|
|
||||||
next: (saved) => {
|
|
||||||
this.activeModal.close()
|
|
||||||
this.succeeded.emit(saved)
|
|
||||||
},
|
|
||||||
error: (e) => {
|
|
||||||
this.saving.set(false)
|
|
||||||
this.failed.emit(e)
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// ng-select needs a stable array between change detection runs, so the
|
|
||||||
// split language list is cached per zone until ocr_language changes.
|
|
||||||
private readonly ocrLanguageCache = new WeakMap<
|
|
||||||
OcrTemplateZone,
|
|
||||||
{ language: string; languages: string[] }
|
|
||||||
>()
|
|
||||||
|
|
||||||
ocrLanguageArray(zone: OcrTemplateZone): string[] {
|
|
||||||
const language = zone.ocr_language || ''
|
|
||||||
const cached = this.ocrLanguageCache.get(zone)
|
|
||||||
if (cached?.language === language) return cached.languages
|
|
||||||
const languages = language.split('+').filter(Boolean)
|
|
||||||
this.ocrLanguageCache.set(zone, { language, languages })
|
|
||||||
return languages
|
|
||||||
}
|
|
||||||
|
|
||||||
setOcrLanguages(zone: OcrTemplateZone, langs: string[]) {
|
|
||||||
zone.ocr_language = (langs ?? []).join('+')
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The field select's value: a built-in target, or a custom field id. */
|
|
||||||
zoneFieldValue(zone: OcrTemplateZone): ZoneFieldSelection {
|
|
||||||
return zone.target === OcrZoneTarget.CustomField
|
|
||||||
? zone.custom_field
|
|
||||||
: zone.target
|
|
||||||
}
|
|
||||||
|
|
||||||
setZoneField(zone: OcrTemplateZone, value: ZoneFieldSelection) {
|
|
||||||
if (typeof value === 'string') {
|
|
||||||
zone.target = value
|
|
||||||
zone.custom_field = null
|
|
||||||
} else {
|
|
||||||
zone.target = OcrZoneTarget.CustomField
|
|
||||||
zone.custom_field = value
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
zonesForField(zone: OcrTemplateZone): OcrTemplateZone[] {
|
|
||||||
const key = getZoneFieldKey(zone)
|
|
||||||
if (!key) return []
|
|
||||||
return this.template.zones.filter((z) => getZoneFieldKey(z) === key)
|
|
||||||
}
|
|
||||||
|
|
||||||
isFieldShared(zone: OcrTemplateZone): boolean {
|
|
||||||
return this.zonesForField(zone).length > 1
|
|
||||||
}
|
|
||||||
|
|
||||||
renameZone(zone: OcrTemplateZone, name: string) {
|
|
||||||
const oldName = zone.name.trim()
|
|
||||||
const format = this.getCombineFormat(zone)
|
|
||||||
if (format) {
|
|
||||||
this.setCombineFormat(
|
|
||||||
zone,
|
|
||||||
format.replace(/\{([^{}]*)\}/g, (token, tokenName: string) =>
|
|
||||||
tokenName.trim() === oldName ? `{${name}}` : token
|
|
||||||
)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
zone.name = name
|
|
||||||
}
|
|
||||||
|
|
||||||
getCombineFormat(zone: OcrTemplateZone): string {
|
|
||||||
return this.template.combine_formats?.[getZoneFieldKey(zone)] ?? ''
|
|
||||||
}
|
|
||||||
|
|
||||||
setCombineFormat(zone: OcrTemplateZone, value: string) {
|
|
||||||
const key = getZoneFieldKey(zone)
|
|
||||||
if (!key) return
|
|
||||||
this.template.combine_formats ??= {}
|
|
||||||
this.template.combine_formats[key] = value
|
|
||||||
}
|
|
||||||
|
|
||||||
defaultCombineFormat(zone: OcrTemplateZone): string {
|
|
||||||
return this.zonesForField(zone)
|
|
||||||
.map((z) => `{${z.name}}`)
|
|
||||||
.join(' ')
|
|
||||||
}
|
|
||||||
|
|
||||||
insertCombineToken(zone: OcrTemplateZone, tokenZone: OcrTemplateZone) {
|
|
||||||
const current = this.getCombineFormat(zone)
|
|
||||||
const sep = current && !current.endsWith(' ') ? ' ' : ''
|
|
||||||
this.setCombineFormat(zone, `${current}${sep}{${tokenZone.name}}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Drop formats that are empty or whose field no longer has several zones. */
|
|
||||||
private pruneCombineFormats() {
|
|
||||||
const formats = this.template.combine_formats
|
|
||||||
if (!formats) return
|
|
||||||
const keys = this.template.zones.map(getZoneFieldKey)
|
|
||||||
for (const [key, format] of Object.entries(formats)) {
|
|
||||||
if (!format || keys.filter((k) => k === key).length < 2) {
|
|
||||||
delete formats[key]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
createField(name?: string) {
|
|
||||||
const zone = this.selectedZone
|
|
||||||
const modal = this.modalService.open(CustomFieldEditDialogComponent)
|
|
||||||
modal.componentInstance.dialogMode.set(EditDialogMode.CREATE)
|
|
||||||
modal.componentInstance.object = { name: name || zone?.name }
|
|
||||||
modal.componentInstance.succeeded
|
|
||||||
.pipe(takeUntil(this.destroy$))
|
|
||||||
.subscribe((field: CustomField) => {
|
|
||||||
this.toastService.showSuccess($localize`Saved field "${field.name}".`)
|
|
||||||
this.customFieldsService.clearCache()
|
|
||||||
this.customFieldsService
|
|
||||||
.listAll()
|
|
||||||
.pipe(takeUntil(this.destroy$))
|
|
||||||
.subscribe((r) => {
|
|
||||||
if (zone && OCR_SUPPORTED_FIELD_TYPES.includes(field.data_type)) {
|
|
||||||
this.setZoneField(zone, field.id)
|
|
||||||
}
|
|
||||||
this.customFields.set(r.results)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
modal.componentInstance.failed
|
|
||||||
.pipe(takeUntil(this.destroy$))
|
|
||||||
.subscribe((e) => {
|
|
||||||
this.toastService.showError($localize`Error saving field.`, e)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
ngOnDestroy() {
|
|
||||||
this.previewResizeObserver?.disconnect()
|
|
||||||
this.cancelZoneTest$.complete()
|
|
||||||
this.destroy$.next()
|
|
||||||
this.destroy$.complete()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-197
@@ -1,197 +0,0 @@
|
|||||||
import {
|
|
||||||
OcrTemplateZone,
|
|
||||||
OcrZoneTarget,
|
|
||||||
OcrZoneTransform,
|
|
||||||
} from 'src/app/data/ocr-template'
|
|
||||||
import {
|
|
||||||
findHandleAt,
|
|
||||||
findZoneAt,
|
|
||||||
getResizeHandles,
|
|
||||||
getZoneDisplayRect,
|
|
||||||
getZonePage,
|
|
||||||
isZoneOnPage,
|
|
||||||
moveZone,
|
|
||||||
resizeZone,
|
|
||||||
} from './zone-geometry'
|
|
||||||
|
|
||||||
function zone(overrides: Partial<OcrTemplateZone> = {}): OcrTemplateZone {
|
|
||||||
return {
|
|
||||||
name: 'Zone',
|
|
||||||
target: OcrZoneTarget.CustomField,
|
|
||||||
custom_field: 1,
|
|
||||||
x: 100,
|
|
||||||
y: 200,
|
|
||||||
width: 300,
|
|
||||||
height: 400,
|
|
||||||
page: 1,
|
|
||||||
ocr_language: 'eng',
|
|
||||||
transform: OcrZoneTransform.Strip,
|
|
||||||
validation_regex: '',
|
|
||||||
order: 0,
|
|
||||||
...overrides,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('OCR template editor geometry', () => {
|
|
||||||
it('normalizes zone pages', () => {
|
|
||||||
expect(getZonePage(zone({ page: 2 }), 0, 5)).toBe(2)
|
|
||||||
expect(getZonePage(zone({ page: -1 }), 0, 5)).toBe(5)
|
|
||||||
expect(getZonePage(zone({ page: -1 }), 2, null)).toBe(3)
|
|
||||||
expect(getZonePage(zone({ page: 0 }), 0, 5)).toBe(1)
|
|
||||||
expect(getZonePage(zone({ page: undefined }), 0, 5)).toBe(1)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('checks whether a zone is on the current preview page', () => {
|
|
||||||
expect(isZoneOnPage(zone({ page: 2 }), 1, 5)).toBe(true)
|
|
||||||
expect(isZoneOnPage(zone({ page: 2 }), 0, 5)).toBe(false)
|
|
||||||
expect(isZoneOnPage(zone({ page: -1 }), 4, 5)).toBe(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('uses natural image coordinates when source dimensions are unset', () => {
|
|
||||||
expect(
|
|
||||||
getZoneDisplayRect(zone({ x: 100, y: 200, width: 300, height: 400 }), {
|
|
||||||
width: 1000,
|
|
||||||
height: 2000,
|
|
||||||
})
|
|
||||||
).toEqual({ x: 100, y: 200, w: 300, h: 400 })
|
|
||||||
})
|
|
||||||
|
|
||||||
it('uses per-zone source dimensions when present', () => {
|
|
||||||
expect(
|
|
||||||
getZoneDisplayRect(
|
|
||||||
zone({
|
|
||||||
x: 100,
|
|
||||||
y: 100,
|
|
||||||
width: 100,
|
|
||||||
height: 100,
|
|
||||||
zone_source_width: 1000,
|
|
||||||
zone_source_height: 1000,
|
|
||||||
}),
|
|
||||||
{ width: 500, height: 750 }
|
|
||||||
)
|
|
||||||
).toEqual({ x: 50, y: 75, w: 50, h: 75 })
|
|
||||||
})
|
|
||||||
|
|
||||||
it('finds zones from topmost to bottommost on the current page', () => {
|
|
||||||
const zones = [
|
|
||||||
zone({ name: 'first', x: 0, y: 0, width: 100, height: 100, page: 1 }),
|
|
||||||
zone({ name: 'second', x: 0, y: 0, width: 50, height: 50, page: 1 }),
|
|
||||||
zone({ name: 'third', x: 0, y: 0, width: 50, height: 50, page: 2 }),
|
|
||||||
]
|
|
||||||
|
|
||||||
expect(
|
|
||||||
findZoneAt({ x: 25, y: 25 }, zones, 0, 2, { width: 100, height: 100 })
|
|
||||||
).toBe(1)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('finds resize handles around a display rect', () => {
|
|
||||||
const rect = { x: 10, y: 20, w: 100, h: 200 }
|
|
||||||
|
|
||||||
expect(findHandleAt({ x: 10, y: 20 }, rect)).toBe('nw')
|
|
||||||
expect(findHandleAt({ x: 110, y: 220 }, rect)).toBe('se')
|
|
||||||
expect(findHandleAt({ x: 60, y: 20 }, rect)).toBe('n')
|
|
||||||
expect(findHandleAt({ x: 90, y: 160 }, rect)).toBeNull()
|
|
||||||
expect(findHandleAt({ x: 19, y: 20 }, rect, 8)).toBeNull()
|
|
||||||
expect(findHandleAt({ x: 19, y: 20 }, rect, 10)).toBe('nw')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('returns no zone when the point is outside every rectangle', () => {
|
|
||||||
expect(
|
|
||||||
findZoneAt({ x: 900, y: 900 }, [zone()], 0, 1, {
|
|
||||||
width: 1000,
|
|
||||||
height: 1000,
|
|
||||||
})
|
|
||||||
).toBeNull()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('resizes north-west edges while keeping the opposite corner fixed', () => {
|
|
||||||
const z = zone({ x: 100, y: 200, width: 300, height: 400 })
|
|
||||||
resizeZone(z, 'nw', { x: 50, y: 100 }, { width: 1000, height: 1000 })
|
|
||||||
expect(z).toMatchObject({ x: 50, y: 100, width: 350, height: 500 })
|
|
||||||
resizeZone(z, 'nw', { x: 900, y: 900 }, { width: 1000, height: 1000 })
|
|
||||||
expect(z).toMatchObject({ x: 390, y: 590, width: 10, height: 10 })
|
|
||||||
})
|
|
||||||
|
|
||||||
it('clamps resized north-west edges to the source image bounds', () => {
|
|
||||||
const z = zone({
|
|
||||||
x: 50,
|
|
||||||
y: 50,
|
|
||||||
width: 100,
|
|
||||||
height: 100,
|
|
||||||
zone_source_width: 200,
|
|
||||||
zone_source_height: 300,
|
|
||||||
})
|
|
||||||
resizeZone(z, 'nw', { x: -50, y: -50 }, { width: 400, height: 600 })
|
|
||||||
expect(z).toMatchObject({ x: 0, y: 0, width: 150, height: 150 })
|
|
||||||
})
|
|
||||||
|
|
||||||
it('uses the rendered handle positions for hit testing', () => {
|
|
||||||
const rect = { x: 10, y: 20, w: 100, h: 200 }
|
|
||||||
const handles = getResizeHandles(rect)
|
|
||||||
|
|
||||||
expect(handles).toEqual([
|
|
||||||
{ handle: 'nw', x: 10, y: 20 },
|
|
||||||
{ handle: 'n', x: 60, y: 20 },
|
|
||||||
{ handle: 'ne', x: 110, y: 20 },
|
|
||||||
{ handle: 'w', x: 10, y: 120 },
|
|
||||||
{ handle: 'e', x: 110, y: 120 },
|
|
||||||
{ handle: 'sw', x: 10, y: 220 },
|
|
||||||
{ handle: 's', x: 60, y: 220 },
|
|
||||||
{ handle: 'se', x: 110, y: 220 },
|
|
||||||
])
|
|
||||||
for (const marker of handles) {
|
|
||||||
expect(findHandleAt(marker, rect)).toBe(marker.handle)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
it('moves zones without leaving source image bounds', () => {
|
|
||||||
const z = zone({ x: 50, y: 50, width: 100, height: 100 })
|
|
||||||
|
|
||||||
moveZone(
|
|
||||||
z,
|
|
||||||
{ x: 500, y: 500 },
|
|
||||||
{ mouseX: 50, mouseY: 50, zoneX: 50, zoneY: 50 },
|
|
||||||
{ width: 500, height: 500 }
|
|
||||||
)
|
|
||||||
|
|
||||||
expect(z.x).toBe(400)
|
|
||||||
expect(z.y).toBe(400)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('resizes zones without leaving source image bounds', () => {
|
|
||||||
const z = zone({
|
|
||||||
x: 50,
|
|
||||||
y: 50,
|
|
||||||
width: 100,
|
|
||||||
height: 100,
|
|
||||||
zone_source_width: 200,
|
|
||||||
zone_source_height: 200,
|
|
||||||
})
|
|
||||||
|
|
||||||
resizeZone(z, 'se', { x: 500, y: 500 }, { width: 500, height: 500 })
|
|
||||||
|
|
||||||
expect(z.width).toBe(150)
|
|
||||||
expect(z.height).toBe(150)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('moves zones in their original source coordinates on a different-size preview', () => {
|
|
||||||
const z = zone({
|
|
||||||
x: 50,
|
|
||||||
y: 50,
|
|
||||||
width: 100,
|
|
||||||
height: 100,
|
|
||||||
zone_source_width: 1000,
|
|
||||||
zone_source_height: 2000,
|
|
||||||
})
|
|
||||||
|
|
||||||
moveZone(
|
|
||||||
z,
|
|
||||||
{ x: 75, y: 75 },
|
|
||||||
{ mouseX: 25, mouseY: 25, zoneX: 50, zoneY: 50 },
|
|
||||||
{ width: 500, height: 500 }
|
|
||||||
)
|
|
||||||
|
|
||||||
expect(z.x).toBe(150)
|
|
||||||
expect(z.y).toBe(250)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
@@ -1,204 +0,0 @@
|
|||||||
import { OcrTemplateZone } from 'src/app/data/ocr-template'
|
|
||||||
|
|
||||||
export interface DrawingRect {
|
|
||||||
startX: number
|
|
||||||
startY: number
|
|
||||||
endX: number
|
|
||||||
endY: number
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface Dimensions {
|
|
||||||
width: number
|
|
||||||
height: number
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface Point {
|
|
||||||
x: number
|
|
||||||
y: number
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface DisplayRect {
|
|
||||||
x: number
|
|
||||||
y: number
|
|
||||||
w: number
|
|
||||||
h: number
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface MoveStart {
|
|
||||||
mouseX: number
|
|
||||||
mouseY: number
|
|
||||||
zoneX: number
|
|
||||||
zoneY: number
|
|
||||||
}
|
|
||||||
|
|
||||||
export type ResizeHandle = 'n' | 's' | 'e' | 'w' | 'ne' | 'nw' | 'se' | 'sw'
|
|
||||||
|
|
||||||
export interface ResizeHandleMarker extends Point {
|
|
||||||
handle: ResizeHandle
|
|
||||||
}
|
|
||||||
|
|
||||||
export const HANDLE_SIZE = 8
|
|
||||||
export const MIN_ZONE_SIZE = 10
|
|
||||||
|
|
||||||
const ZONE_COLORS = [
|
|
||||||
'#4f8ff7',
|
|
||||||
'#ff6b6b',
|
|
||||||
'#51cf66',
|
|
||||||
'#ffd43b',
|
|
||||||
'#cc5de8',
|
|
||||||
'#ff922b',
|
|
||||||
'#20c997',
|
|
||||||
'#e599f7',
|
|
||||||
]
|
|
||||||
|
|
||||||
/** Outline color for a zone, shared by the preview overlay and the zone list. */
|
|
||||||
export function getZoneColor(index: number): string {
|
|
||||||
return ZONE_COLORS[index % ZONE_COLORS.length]
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getZonePage(
|
|
||||||
zone: OcrTemplateZone,
|
|
||||||
previewPage: number,
|
|
||||||
previewPageCount: number | null
|
|
||||||
): number {
|
|
||||||
const page = zone.page ?? 1
|
|
||||||
if (page === -1) return previewPageCount ?? previewPage + 1
|
|
||||||
return Math.max(page, 1)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function isZoneOnPage(
|
|
||||||
zone: OcrTemplateZone,
|
|
||||||
previewPage: number,
|
|
||||||
previewPageCount: number | null
|
|
||||||
): boolean {
|
|
||||||
return getZonePage(zone, previewPage, previewPageCount) === previewPage + 1
|
|
||||||
}
|
|
||||||
|
|
||||||
function getZoneSourceSize(
|
|
||||||
zone: OcrTemplateZone,
|
|
||||||
imageSize: Dimensions
|
|
||||||
): Dimensions {
|
|
||||||
return {
|
|
||||||
width: zone.zone_source_width || imageSize.width,
|
|
||||||
height: zone.zone_source_height || imageSize.height,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getZoneDisplayRect(
|
|
||||||
zone: OcrTemplateZone,
|
|
||||||
imageSize: Dimensions
|
|
||||||
): DisplayRect {
|
|
||||||
const sourceSize = getZoneSourceSize(zone, imageSize)
|
|
||||||
// The SVG viewBox uses the preview image's natural dimensions.
|
|
||||||
const scaleX = imageSize.width / sourceSize.width
|
|
||||||
const scaleY = imageSize.height / sourceSize.height
|
|
||||||
|
|
||||||
return {
|
|
||||||
x: zone.x * scaleX,
|
|
||||||
y: zone.y * scaleY,
|
|
||||||
w: zone.width * scaleX,
|
|
||||||
h: zone.height * scaleY,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getResizeHandles(rect: DisplayRect): ResizeHandleMarker[] {
|
|
||||||
return [
|
|
||||||
{ handle: 'nw', x: rect.x, y: rect.y },
|
|
||||||
{ handle: 'n', x: rect.x + rect.w / 2, y: rect.y },
|
|
||||||
{ handle: 'ne', x: rect.x + rect.w, y: rect.y },
|
|
||||||
{ handle: 'w', x: rect.x, y: rect.y + rect.h / 2 },
|
|
||||||
{ handle: 'e', x: rect.x + rect.w, y: rect.y + rect.h / 2 },
|
|
||||||
{ handle: 'sw', x: rect.x, y: rect.y + rect.h },
|
|
||||||
{ handle: 's', x: rect.x + rect.w / 2, y: rect.y + rect.h },
|
|
||||||
{ handle: 'se', x: rect.x + rect.w, y: rect.y + rect.h },
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
export function findHandleAt(
|
|
||||||
point: Point,
|
|
||||||
rect: DisplayRect,
|
|
||||||
handleSize = HANDLE_SIZE
|
|
||||||
): ResizeHandle | null {
|
|
||||||
return (
|
|
||||||
getResizeHandles(rect).find(
|
|
||||||
({ x, y }) =>
|
|
||||||
Math.abs(point.x - x) <= handleSize &&
|
|
||||||
Math.abs(point.y - y) <= handleSize
|
|
||||||
)?.handle ?? null
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function findZoneAt(
|
|
||||||
point: Point,
|
|
||||||
zones: OcrTemplateZone[],
|
|
||||||
previewPage: number,
|
|
||||||
previewPageCount: number | null,
|
|
||||||
imageSize: Dimensions
|
|
||||||
): number | null {
|
|
||||||
for (let i = zones.length - 1; i >= 0; i--) {
|
|
||||||
const zone = zones[i]
|
|
||||||
if (!isZoneOnPage(zone, previewPage, previewPageCount)) continue
|
|
||||||
const rect = getZoneDisplayRect(zone, imageSize)
|
|
||||||
|
|
||||||
if (
|
|
||||||
point.x >= rect.x &&
|
|
||||||
point.x <= rect.x + rect.w &&
|
|
||||||
point.y >= rect.y &&
|
|
||||||
point.y <= rect.y + rect.h
|
|
||||||
) {
|
|
||||||
return i
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
export function moveZone(
|
|
||||||
zone: OcrTemplateZone,
|
|
||||||
point: Point,
|
|
||||||
moveStart: MoveStart,
|
|
||||||
imageSize: Dimensions
|
|
||||||
) {
|
|
||||||
const sourceSize = getZoneSourceSize(zone, imageSize)
|
|
||||||
const scaleX = sourceSize.width / imageSize.width
|
|
||||||
const scaleY = sourceSize.height / imageSize.height
|
|
||||||
const dx = Math.round((point.x - moveStart.mouseX) * scaleX)
|
|
||||||
const dy = Math.round((point.y - moveStart.mouseY) * scaleY)
|
|
||||||
|
|
||||||
zone.x = clamp(moveStart.zoneX + dx, 0, sourceSize.width - zone.width)
|
|
||||||
zone.y = clamp(moveStart.zoneY + dy, 0, sourceSize.height - zone.height)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function resizeZone(
|
|
||||||
zone: OcrTemplateZone,
|
|
||||||
handle: ResizeHandle,
|
|
||||||
point: Point,
|
|
||||||
imageSize: Dimensions
|
|
||||||
) {
|
|
||||||
const sourceSize = getZoneSourceSize(zone, imageSize)
|
|
||||||
const scaleX = sourceSize.width / imageSize.width
|
|
||||||
const scaleY = sourceSize.height / imageSize.height
|
|
||||||
const imageX = clamp(Math.round(point.x * scaleX), 0, sourceSize.width)
|
|
||||||
const imageY = clamp(Math.round(point.y * scaleY), 0, sourceSize.height)
|
|
||||||
|
|
||||||
if (handle.includes('w')) {
|
|
||||||
const right = Math.min(zone.x + zone.width, sourceSize.width)
|
|
||||||
zone.x = clamp(imageX, 0, right - MIN_ZONE_SIZE)
|
|
||||||
zone.width = right - zone.x
|
|
||||||
}
|
|
||||||
if (handle.includes('e')) {
|
|
||||||
zone.width = Math.max(MIN_ZONE_SIZE, imageX - zone.x)
|
|
||||||
}
|
|
||||||
if (handle.includes('n')) {
|
|
||||||
const bottom = Math.min(zone.y + zone.height, sourceSize.height)
|
|
||||||
zone.y = clamp(imageY, 0, bottom - MIN_ZONE_SIZE)
|
|
||||||
zone.height = bottom - zone.y
|
|
||||||
}
|
|
||||||
if (handle.includes('s')) {
|
|
||||||
zone.height = Math.max(MIN_ZONE_SIZE, imageY - zone.y)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function clamp(value: number, min: number, max: number): number {
|
|
||||||
return Math.max(min, Math.min(value, max))
|
|
||||||
}
|
|
||||||
@@ -1,75 +0,0 @@
|
|||||||
<pngx-page-header
|
|
||||||
title="OCR Templates"
|
|
||||||
i18n-title
|
|
||||||
info="Define extraction zones on document types to automatically populate custom fields via OCR."
|
|
||||||
i18n-info
|
|
||||||
>
|
|
||||||
<button type="button" class="btn btn-sm btn-outline-primary" (click)="editTemplate()" *pngxIfPermissions="{ action: PermissionAction.Add, type: PermissionType.OcrTemplate }">
|
|
||||||
<pngx-bs-icon name="plus-circle" class="me-1"></pngx-bs-icon><ng-container i18n>Add Template</ng-container>
|
|
||||||
</button>
|
|
||||||
</pngx-page-header>
|
|
||||||
|
|
||||||
<ul class="list-group">
|
|
||||||
|
|
||||||
<li class="list-group-item">
|
|
||||||
<div class="row">
|
|
||||||
<div class="col" i18n>Name</div>
|
|
||||||
<div class="col d-none d-sm-flex" i18n>Matching</div>
|
|
||||||
<div class="col d-none d-sm-flex" i18n>Zones</div>
|
|
||||||
<div class="col" i18n>Status</div>
|
|
||||||
<div class="col" i18n>Actions</div>
|
|
||||||
</div>
|
|
||||||
</li>
|
|
||||||
|
|
||||||
@if (loading() && templates().length === 0) {
|
|
||||||
<li class="list-group-item">
|
|
||||||
<output class="spinner-border spinner-border-sm me-2"></output>
|
|
||||||
<ng-container i18n>Loading...</ng-container>
|
|
||||||
</li>
|
|
||||||
}
|
|
||||||
|
|
||||||
@for (template of templates(); track template.id) {
|
|
||||||
<li class="list-group-item">
|
|
||||||
<div class="row fade" [class.show]="show()">
|
|
||||||
<div class="col d-flex align-items-center"><button class="btn btn-link p-0 text-start" type="button" (click)="editTemplate(template)" [disabled]="!userCanEdit(template)">{{template.name}}</button></div>
|
|
||||||
<div class="col d-flex align-items-center d-none d-sm-flex">{{getMatching(template)}}</div>
|
|
||||||
<div class="col d-flex align-items-center d-none d-sm-flex"><code>{{template.zones.length}}</code></div>
|
|
||||||
<div class="col d-flex align-items-center">
|
|
||||||
<div class="form-check form-switch mb-0">
|
|
||||||
<input type="checkbox" class="form-check-input cursor-pointer" [id]="template.id+'_enable'" [(ngModel)]="template.enabled" (change)="toggleTemplateEnabled(template)" [disabled]="!userCanEdit(template)" *pngxIfPermissions="{ action: PermissionAction.Change, type: PermissionType.OcrTemplate }">
|
|
||||||
<label class="form-check-label cursor-pointer" [for]="template.id+'_enable'">
|
|
||||||
<code> @if(template.enabled) { <ng-container i18n>Enabled</ng-container> } @else { <span i18n class="text-muted">Disabled</span> }</code>
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="col">
|
|
||||||
|
|
||||||
<div class="btn-group d-block d-sm-none">
|
|
||||||
<div ngbDropdown container="body" class="d-inline-block">
|
|
||||||
<button type="button" class="btn btn-link" id="actionsMenuMobile{{template.id}}" (click)="$event.stopPropagation()" ngbDropdownToggle>
|
|
||||||
<pngx-bs-icon name="three-dots-vertical"></pngx-bs-icon>
|
|
||||||
</button>
|
|
||||||
<div ngbDropdownMenu aria-labelledby="actionsMenuMobile{{template.id}}">
|
|
||||||
<button (click)="editTemplate(template)" [disabled]="!userCanEdit(template)" *pngxIfPermissions="{ action: PermissionAction.Change, type: PermissionType.OcrTemplate }" ngbDropdownItem i18n>Edit</button>
|
|
||||||
<button (click)="deleteTemplate(template)" [disabled]="!permissionsService.currentUserOwnsObject(template)" *pngxIfPermissions="{ action: PermissionAction.Delete, type: PermissionType.OcrTemplate }" ngbDropdownItem i18n>Delete</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="btn-toolbar d-none d-sm-flex gap-2" role="toolbar">
|
|
||||||
<div class="btn-group">
|
|
||||||
<button *pngxIfPermissions="{ action: PermissionAction.Change, type: PermissionType.OcrTemplate }" [disabled]="!userCanEdit(template)" class="btn btn-sm btn-outline-secondary" type="button" (click)="editTemplate(template)">
|
|
||||||
<pngx-bs-icon width="1em" height="1em" name="pencil" class="me-1"></pngx-bs-icon><ng-container i18n>Edit</ng-container>
|
|
||||||
</button>
|
|
||||||
<button *pngxIfPermissions="{ action: PermissionAction.Delete, type: PermissionType.OcrTemplate }" [disabled]="!permissionsService.currentUserOwnsObject(template)" class="btn btn-sm btn-outline-danger" type="button" (click)="deleteTemplate(template)">
|
|
||||||
<pngx-bs-icon width="1em" height="1em" name="trash" class="me-1"></pngx-bs-icon><ng-container i18n>Delete</ng-container>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</li>
|
|
||||||
}
|
|
||||||
@if (!loading() && templates().length === 0) {
|
|
||||||
<li class="list-group-item" [class.show]="show()" i18n>No OCR templates defined.</li>
|
|
||||||
}
|
|
||||||
</ul>
|
|
||||||
@@ -1,300 +0,0 @@
|
|||||||
import { provideHttpClient, withInterceptorsFromDi } from '@angular/common/http'
|
|
||||||
import { provideHttpClientTesting } from '@angular/common/http/testing'
|
|
||||||
import { ComponentFixture, TestBed } from '@angular/core/testing'
|
|
||||||
import { By } from '@angular/platform-browser'
|
|
||||||
import { NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap'
|
|
||||||
import { of, throwError } from 'rxjs'
|
|
||||||
import { MATCH_LITERAL, MATCH_NONE } from 'src/app/data/matching-model'
|
|
||||||
import { OcrTemplate } from 'src/app/data/ocr-template'
|
|
||||||
import { User } from 'src/app/data/user'
|
|
||||||
import { DirtyFormGuard } from 'src/app/guards/dirty-form.guard'
|
|
||||||
import { PermissionsService } from 'src/app/services/permissions.service'
|
|
||||||
import { OcrTemplateService } from 'src/app/services/rest/ocr-template.service'
|
|
||||||
import { UserService } from 'src/app/services/rest/user.service'
|
|
||||||
import { ToastService } from 'src/app/services/toast.service'
|
|
||||||
import { ConfirmDialogComponent } from '../../common/confirm-dialog/confirm-dialog.component'
|
|
||||||
import { OcrTemplateEditorComponent } from './ocr-template-editor/ocr-template-editor.component'
|
|
||||||
import { OcrTemplatesComponent } from './ocr-templates.component'
|
|
||||||
import { BootstrapIconComponent } from 'src/app/components/common/bootstrap-icon/bootstrap-icon.component'
|
|
||||||
|
|
||||||
const templates: OcrTemplate[] = [
|
|
||||||
{
|
|
||||||
id: 1,
|
|
||||||
name: 'Invoices',
|
|
||||||
match: 'Northwind',
|
|
||||||
matching_algorithm: MATCH_LITERAL,
|
|
||||||
sample_document: null,
|
|
||||||
source_width: 0,
|
|
||||||
source_height: 0,
|
|
||||||
enabled: true,
|
|
||||||
zones: [],
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
describe('OcrTemplatesComponent', () => {
|
|
||||||
let component: OcrTemplatesComponent
|
|
||||||
let fixture: ComponentFixture<OcrTemplatesComponent>
|
|
||||||
let ocrTemplateService: OcrTemplateService
|
|
||||||
let modalService: NgbModal
|
|
||||||
let toastService: ToastService
|
|
||||||
let modal: NgbModalRef
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
TestBed.configureTestingModule({
|
|
||||||
imports: [OcrTemplatesComponent, BootstrapIconComponent],
|
|
||||||
providers: [
|
|
||||||
provideHttpClient(withInterceptorsFromDi()),
|
|
||||||
provideHttpClientTesting(),
|
|
||||||
],
|
|
||||||
})
|
|
||||||
|
|
||||||
TestBed.inject(PermissionsService).initialize(
|
|
||||||
[
|
|
||||||
'view_ocrtemplate',
|
|
||||||
'add_ocrtemplate',
|
|
||||||
'change_ocrtemplate',
|
|
||||||
'delete_ocrtemplate',
|
|
||||||
],
|
|
||||||
{ id: 1, groups: [], is_superuser: false } as User
|
|
||||||
)
|
|
||||||
jest
|
|
||||||
.spyOn(TestBed.inject(UserService), 'listAll')
|
|
||||||
.mockReturnValue(of({ count: 0, all: [], results: [] }))
|
|
||||||
|
|
||||||
ocrTemplateService = TestBed.inject(OcrTemplateService)
|
|
||||||
jest
|
|
||||||
.spyOn(ocrTemplateService, 'listAll')
|
|
||||||
.mockReturnValue(of({ count: 1, all: [1], results: templates }))
|
|
||||||
modalService = TestBed.inject(NgbModal)
|
|
||||||
modalService.activeInstances.subscribe((m) => (modal = m[m.length - 1]))
|
|
||||||
toastService = TestBed.inject(ToastService)
|
|
||||||
fixture = TestBed.createComponent(OcrTemplatesComponent)
|
|
||||||
component = fixture.componentInstance
|
|
||||||
fixture.detectChanges()
|
|
||||||
})
|
|
||||||
|
|
||||||
afterEach(() => modalService.dismissAll())
|
|
||||||
|
|
||||||
it('should show templates with their matching', () => {
|
|
||||||
const text = fixture.nativeElement.textContent
|
|
||||||
expect(text).toContain('Invoices')
|
|
||||||
expect(text).toContain('Exact match: Northwind')
|
|
||||||
|
|
||||||
expect(
|
|
||||||
component.getMatching({ ...templates[0], matching_algorithm: MATCH_NONE })
|
|
||||||
).toEqual('None')
|
|
||||||
expect(component.getMatching({ ...templates[0], match: '' })).toEqual('-')
|
|
||||||
})
|
|
||||||
|
|
||||||
it.each([
|
|
||||||
{
|
|
||||||
name: 'owned',
|
|
||||||
owner: 1,
|
|
||||||
user_can_change: true,
|
|
||||||
editable: true,
|
|
||||||
deletable: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'unowned',
|
|
||||||
owner: null,
|
|
||||||
user_can_change: true,
|
|
||||||
editable: true,
|
|
||||||
deletable: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'view-only shared',
|
|
||||||
owner: 2,
|
|
||||||
user_can_change: false,
|
|
||||||
editable: false,
|
|
||||||
deletable: false,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'editable shared',
|
|
||||||
owner: 2,
|
|
||||||
user_can_change: true,
|
|
||||||
editable: true,
|
|
||||||
deletable: false,
|
|
||||||
},
|
|
||||||
])(
|
|
||||||
'should respect permissions for $name templates',
|
|
||||||
async ({ owner, user_can_change, editable, deletable }) => {
|
|
||||||
const template = { ...templates[0], owner, user_can_change }
|
|
||||||
component.templates.set([template])
|
|
||||||
fixture.detectChanges()
|
|
||||||
await fixture.whenStable()
|
|
||||||
|
|
||||||
expect(fixture.nativeElement.querySelector('.text-start').disabled).toBe(
|
|
||||||
!editable
|
|
||||||
)
|
|
||||||
expect(
|
|
||||||
fixture.nativeElement.querySelector('.form-switch input').disabled
|
|
||||||
).toBe(!editable)
|
|
||||||
const buttons = Array.from<HTMLButtonElement>(
|
|
||||||
fixture.nativeElement.querySelectorAll('button')
|
|
||||||
)
|
|
||||||
for (const button of buttons.filter(
|
|
||||||
(button) => button.textContent.trim() === 'Edit'
|
|
||||||
)) {
|
|
||||||
expect(button.disabled).toBe(!editable)
|
|
||||||
}
|
|
||||||
for (const button of buttons.filter(
|
|
||||||
(button) => button.textContent.trim() === 'Delete'
|
|
||||||
)) {
|
|
||||||
expect(button.disabled).toBe(!deletable)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
it('should allow a superuser to manage another users template', () => {
|
|
||||||
TestBed.inject(PermissionsService).initialize([], {
|
|
||||||
id: 1,
|
|
||||||
is_superuser: true,
|
|
||||||
} as User)
|
|
||||||
component.templates.set([
|
|
||||||
{ ...templates[0], owner: 2, user_can_change: false },
|
|
||||||
])
|
|
||||||
fixture.detectChanges()
|
|
||||||
expect(fixture.nativeElement.querySelector('.text-start').disabled).toBe(
|
|
||||||
false
|
|
||||||
)
|
|
||||||
expect(
|
|
||||||
fixture.nativeElement.querySelector('.btn-outline-danger').disabled
|
|
||||||
).toBe(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should not open mutation dialogs or patch a view-only template', () => {
|
|
||||||
const template = { ...templates[0], owner: 2, user_can_change: false }
|
|
||||||
const open = jest.spyOn(modalService, 'open')
|
|
||||||
const patch = jest.spyOn(ocrTemplateService, 'patch')
|
|
||||||
component.editTemplate(template)
|
|
||||||
component.toggleTemplateEnabled(template)
|
|
||||||
component.deleteTemplate(template)
|
|
||||||
expect(open).not.toHaveBeenCalled()
|
|
||||||
expect(patch).not.toHaveBeenCalled()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should require global edit permission even for an owned template', () => {
|
|
||||||
TestBed.inject(PermissionsService).initialize(['view_ocrtemplate'], {
|
|
||||||
id: 1,
|
|
||||||
} as User)
|
|
||||||
fixture.destroy()
|
|
||||||
fixture = TestBed.createComponent(OcrTemplatesComponent)
|
|
||||||
component = fixture.componentInstance
|
|
||||||
fixture.detectChanges()
|
|
||||||
expect(fixture.nativeElement.querySelector('.text-start').disabled).toBe(
|
|
||||||
true
|
|
||||||
)
|
|
||||||
expect(fixture.nativeElement.querySelector('.form-switch input')).toBeNull()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should support create, show notification on error / success', () => {
|
|
||||||
const toastErrorSpy = jest.spyOn(toastService, 'showError')
|
|
||||||
const toastSuccessSpy = jest.spyOn(toastService, 'showSuccess')
|
|
||||||
const reloadSpy = jest.spyOn(component, 'reload')
|
|
||||||
|
|
||||||
fixture.debugElement
|
|
||||||
.queryAll(By.css('pngx-page-header button'))
|
|
||||||
.find((button) => button.nativeElement.textContent.includes('Add'))
|
|
||||||
.triggerEventHandler('click')
|
|
||||||
|
|
||||||
const editor = modal.componentInstance as OcrTemplateEditorComponent
|
|
||||||
expect(editor).toBeInstanceOf(OcrTemplateEditorComponent)
|
|
||||||
expect(editor.object).toBeUndefined()
|
|
||||||
|
|
||||||
editor.failed.emit({ error: 'error creating template' })
|
|
||||||
expect(toastErrorSpy).toHaveBeenCalled()
|
|
||||||
expect(reloadSpy).not.toHaveBeenCalled()
|
|
||||||
|
|
||||||
editor.succeeded.emit(templates[0])
|
|
||||||
expect(toastSuccessSpy).toHaveBeenCalled()
|
|
||||||
expect(reloadSpy).toHaveBeenCalled()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should pass the template to the editor', () => {
|
|
||||||
component.editTemplate(templates[0])
|
|
||||||
expect(modal.componentInstance.object).toBe(templates[0])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should confirm closing the editor with unsaved changes', async () => {
|
|
||||||
const confirmSpy = jest
|
|
||||||
.spyOn(TestBed.inject(DirtyFormGuard), 'confirmChanges')
|
|
||||||
.mockReturnValue(of(false))
|
|
||||||
component.editTemplate()
|
|
||||||
const editor = modal.componentInstance as OcrTemplateEditorComponent
|
|
||||||
editor.ngOnInit()
|
|
||||||
|
|
||||||
modal.dismiss()
|
|
||||||
await fixture.whenStable()
|
|
||||||
expect(confirmSpy).not.toHaveBeenCalled()
|
|
||||||
|
|
||||||
component.editTemplate()
|
|
||||||
const dirtyEditor = modal.componentInstance as OcrTemplateEditorComponent
|
|
||||||
dirtyEditor.ngOnInit()
|
|
||||||
dirtyEditor.template.name = 'Changed'
|
|
||||||
modal.dismiss()
|
|
||||||
await fixture.whenStable()
|
|
||||||
expect(confirmSpy).toHaveBeenCalled()
|
|
||||||
expect(modalService.hasOpenModals()).toBe(true)
|
|
||||||
|
|
||||||
dirtyEditor.saving.set(true)
|
|
||||||
confirmSpy.mockClear()
|
|
||||||
modal.dismiss()
|
|
||||||
await fixture.whenStable()
|
|
||||||
expect(confirmSpy).not.toHaveBeenCalled()
|
|
||||||
expect(modalService.hasOpenModals()).toBe(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should only send the enabled flag when toggling', () => {
|
|
||||||
const patchSpy = jest
|
|
||||||
.spyOn(ocrTemplateService, 'patch')
|
|
||||||
.mockReturnValueOnce(throwError(() => new Error('error toggling')))
|
|
||||||
.mockReturnValueOnce(of(templates[0]))
|
|
||||||
const toastErrorSpy = jest.spyOn(toastService, 'showError')
|
|
||||||
const toastSuccessSpy = jest.spyOn(toastService, 'showSuccess')
|
|
||||||
const reloadSpy = jest.spyOn(component, 'reload')
|
|
||||||
|
|
||||||
const toggle = fixture.debugElement.query(By.css('.form-switch input'))
|
|
||||||
toggle.nativeElement.click()
|
|
||||||
expect(patchSpy).toHaveBeenCalledWith({ id: 1, enabled: false })
|
|
||||||
expect(toastErrorSpy).toHaveBeenCalled()
|
|
||||||
expect(reloadSpy).toHaveBeenCalledTimes(1)
|
|
||||||
|
|
||||||
component.toggleTemplateEnabled(templates[0])
|
|
||||||
expect(toastSuccessSpy).toHaveBeenCalled()
|
|
||||||
expect(reloadSpy).toHaveBeenCalledTimes(2)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should support delete, show notification on error / success', () => {
|
|
||||||
const toastErrorSpy = jest.spyOn(toastService, 'showError')
|
|
||||||
const toastSuccessSpy = jest.spyOn(toastService, 'showSuccess')
|
|
||||||
const deleteSpy = jest.spyOn(ocrTemplateService, 'delete')
|
|
||||||
const reloadSpy = jest.spyOn(component, 'reload')
|
|
||||||
|
|
||||||
component.deleteTemplate(templates[0])
|
|
||||||
const dialog = modal.componentInstance as ConfirmDialogComponent
|
|
||||||
|
|
||||||
deleteSpy.mockReturnValueOnce(throwError(() => new Error('error deleting')))
|
|
||||||
dialog.confirmClicked.emit()
|
|
||||||
expect(toastErrorSpy).toHaveBeenCalled()
|
|
||||||
expect(dialog.buttonsEnabled()).toBe(true)
|
|
||||||
expect(reloadSpy).not.toHaveBeenCalled()
|
|
||||||
|
|
||||||
deleteSpy.mockReturnValueOnce(of(true))
|
|
||||||
dialog.confirmClicked.emit()
|
|
||||||
expect(toastSuccessSpy).toHaveBeenCalled()
|
|
||||||
expect(reloadSpy).toHaveBeenCalled()
|
|
||||||
})
|
|
||||||
|
|
||||||
it.each([true, false])(
|
|
||||||
'reports the enabled state %s after the update succeeds',
|
|
||||||
(enabled) => {
|
|
||||||
const template = { ...templates[0], enabled }
|
|
||||||
jest.spyOn(ocrTemplateService, 'patch').mockReturnValue(of(template))
|
|
||||||
const toast = jest.spyOn(toastService, 'showSuccess')
|
|
||||||
component.toggleTemplateEnabled(template)
|
|
||||||
expect(toast).toHaveBeenCalledWith(
|
|
||||||
`${enabled ? 'Enabled' : 'Disabled'} OCR template "${template.name}"`
|
|
||||||
)
|
|
||||||
}
|
|
||||||
)
|
|
||||||
})
|
|
||||||
@@ -1,185 +0,0 @@
|
|||||||
import { Component, OnInit, inject, signal } from '@angular/core'
|
|
||||||
import { FormsModule } from '@angular/forms'
|
|
||||||
import { NgbDropdownModule, NgbModal } from '@ng-bootstrap/ng-bootstrap'
|
|
||||||
import { BootstrapIconComponent } from 'src/app/components/common/bootstrap-icon/bootstrap-icon.component'
|
|
||||||
import { firstValueFrom, takeUntil, tap } from 'rxjs'
|
|
||||||
import { MATCH_NONE, MATCHING_ALGORITHMS } from 'src/app/data/matching-model'
|
|
||||||
import { OcrTemplate } from 'src/app/data/ocr-template'
|
|
||||||
import { IfPermissionsDirective } from 'src/app/directives/if-permissions.directive'
|
|
||||||
import { DirtyFormGuard } from 'src/app/guards/dirty-form.guard'
|
|
||||||
import {
|
|
||||||
PermissionAction,
|
|
||||||
PermissionType,
|
|
||||||
PermissionsService,
|
|
||||||
} from 'src/app/services/permissions.service'
|
|
||||||
import { OcrTemplateService } from 'src/app/services/rest/ocr-template.service'
|
|
||||||
import { ToastService } from 'src/app/services/toast.service'
|
|
||||||
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'
|
|
||||||
import { OcrTemplateEditorComponent } from './ocr-template-editor/ocr-template-editor.component'
|
|
||||||
|
|
||||||
@Component({
|
|
||||||
selector: 'pngx-ocr-templates',
|
|
||||||
templateUrl: './ocr-templates.component.html',
|
|
||||||
imports: [
|
|
||||||
PageHeaderComponent,
|
|
||||||
IfPermissionsDirective,
|
|
||||||
FormsModule,
|
|
||||||
NgbDropdownModule,
|
|
||||||
BootstrapIconComponent,
|
|
||||||
],
|
|
||||||
})
|
|
||||||
export class OcrTemplatesComponent
|
|
||||||
extends LoadingComponentWithPermissions
|
|
||||||
implements OnInit
|
|
||||||
{
|
|
||||||
private readonly ocrTemplateService = inject(OcrTemplateService)
|
|
||||||
public readonly permissionsService = inject(PermissionsService)
|
|
||||||
private readonly modalService = inject(NgbModal)
|
|
||||||
private readonly dirtyFormGuard = inject(DirtyFormGuard)
|
|
||||||
private readonly toastService = inject(ToastService)
|
|
||||||
|
|
||||||
public readonly templates = signal<OcrTemplate[]>([])
|
|
||||||
|
|
||||||
ngOnInit() {
|
|
||||||
this.reload()
|
|
||||||
}
|
|
||||||
|
|
||||||
reload() {
|
|
||||||
this.loading.set(true)
|
|
||||||
this.ocrTemplateService
|
|
||||||
.listAll()
|
|
||||||
.pipe(
|
|
||||||
takeUntil(this.unsubscribeNotifier),
|
|
||||||
tap((r) => this.templates.set(r.results))
|
|
||||||
)
|
|
||||||
.subscribe(() => {
|
|
||||||
this.show.set(true)
|
|
||||||
this.loading.set(false)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
getMatching(template: OcrTemplate): string {
|
|
||||||
if (template.matching_algorithm === MATCH_NONE) {
|
|
||||||
return $localize`None`
|
|
||||||
}
|
|
||||||
if (!template.match) {
|
|
||||||
return '-'
|
|
||||||
}
|
|
||||||
const algorithm = MATCHING_ALGORITHMS.find(
|
|
||||||
(a) => a.id === template.matching_algorithm
|
|
||||||
)
|
|
||||||
return `${algorithm?.shortName}: ${template.match}`
|
|
||||||
}
|
|
||||||
|
|
||||||
editTemplate(template?: OcrTemplate) {
|
|
||||||
if (template && !this.userCanEdit(template)) return
|
|
||||||
const modal = this.modalService.open(OcrTemplateEditorComponent, {
|
|
||||||
backdrop: 'static',
|
|
||||||
keyboard: false,
|
|
||||||
size: 'xxl',
|
|
||||||
fullscreen: 'lg',
|
|
||||||
scrollable: true,
|
|
||||||
ariaLabelledBy: 'ocr-template-editor-title',
|
|
||||||
beforeDismiss: () => {
|
|
||||||
const editor: OcrTemplateEditorComponent = modal.componentInstance
|
|
||||||
if (editor.saving()) return false
|
|
||||||
if (!editor.isDirty) return true
|
|
||||||
return firstValueFrom(
|
|
||||||
this.dirtyFormGuard.confirmChanges(undefined, $localize`Close`)
|
|
||||||
)
|
|
||||||
},
|
|
||||||
})
|
|
||||||
modal.componentInstance.object = template
|
|
||||||
modal.componentInstance.succeeded
|
|
||||||
.pipe(takeUntil(this.unsubscribeNotifier))
|
|
||||||
.subscribe((saved: OcrTemplate) => {
|
|
||||||
this.toastService.showSuccess(
|
|
||||||
$localize`Saved OCR template "${saved.name}".`
|
|
||||||
)
|
|
||||||
this.ocrTemplateService.clearCache()
|
|
||||||
this.reload()
|
|
||||||
})
|
|
||||||
modal.componentInstance.failed
|
|
||||||
.pipe(takeUntil(this.unsubscribeNotifier))
|
|
||||||
.subscribe((e) => {
|
|
||||||
this.toastService.showError($localize`Error saving OCR template.`, e)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
toggleTemplateEnabled(template: OcrTemplate) {
|
|
||||||
if (!this.userCanEdit(template)) return
|
|
||||||
this.ocrTemplateService
|
|
||||||
.patch({ id: template.id, enabled: template.enabled } as OcrTemplate)
|
|
||||||
.subscribe({
|
|
||||||
next: () => {
|
|
||||||
this.toastService.showSuccess(
|
|
||||||
template.enabled
|
|
||||||
? $localize`Enabled OCR template "${template.name}"`
|
|
||||||
: $localize`Disabled OCR template "${template.name}"`
|
|
||||||
)
|
|
||||||
this.reload()
|
|
||||||
},
|
|
||||||
error: (e) => {
|
|
||||||
this.toastService.showError(
|
|
||||||
$localize`Error toggling OCR template "${template.name}".`,
|
|
||||||
e
|
|
||||||
)
|
|
||||||
this.reload()
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
deleteTemplate(template: OcrTemplate) {
|
|
||||||
if (
|
|
||||||
!this.permissionsService.currentUserCan(
|
|
||||||
PermissionAction.Delete,
|
|
||||||
PermissionType.OcrTemplate
|
|
||||||
) ||
|
|
||||||
!this.permissionsService.currentUserOwnsObject(template)
|
|
||||||
)
|
|
||||||
return
|
|
||||||
const modal = this.modalService.open(ConfirmDialogComponent, {
|
|
||||||
backdrop: 'static',
|
|
||||||
})
|
|
||||||
modal.componentInstance.title = $localize`Confirm delete OCR template`
|
|
||||||
modal.componentInstance.messageBold = $localize`This operation will permanently delete this OCR template.`
|
|
||||||
modal.componentInstance.message = $localize`This operation cannot be undone.`
|
|
||||||
modal.componentInstance.btnClass = 'btn-danger'
|
|
||||||
modal.componentInstance.btnCaption = $localize`Proceed`
|
|
||||||
modal.componentInstance.confirmClicked.subscribe(() => {
|
|
||||||
modal.componentInstance.buttonsEnabled.set(false)
|
|
||||||
this.ocrTemplateService.delete(template).subscribe({
|
|
||||||
next: () => {
|
|
||||||
modal.close()
|
|
||||||
this.toastService.showSuccess(
|
|
||||||
$localize`Deleted OCR template "${template.name}".`
|
|
||||||
)
|
|
||||||
this.ocrTemplateService.clearCache()
|
|
||||||
this.reload()
|
|
||||||
},
|
|
||||||
error: (e) => {
|
|
||||||
modal.componentInstance.buttonsEnabled.set(true)
|
|
||||||
this.toastService.showError(
|
|
||||||
$localize`Error deleting OCR template "${template.name}".`,
|
|
||||||
e
|
|
||||||
)
|
|
||||||
},
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
userCanEdit(template: OcrTemplate): boolean {
|
|
||||||
return (
|
|
||||||
this.permissionsService.currentUserCan(
|
|
||||||
PermissionAction.Change,
|
|
||||||
PermissionType.OcrTemplate
|
|
||||||
) &&
|
|
||||||
this.permissionsService.currentUserHasObjectPermissions(
|
|
||||||
PermissionAction.Change,
|
|
||||||
template
|
|
||||||
)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,105 +0,0 @@
|
|||||||
import { CustomFieldDataType } from './custom-field'
|
|
||||||
import { MatchingModel } from './matching-model'
|
|
||||||
import { ObjectWithPermissions } from './object-with-permissions'
|
|
||||||
|
|
||||||
export enum OcrZoneTarget {
|
|
||||||
CustomField = 'custom_field',
|
|
||||||
Title = 'title',
|
|
||||||
Asn = 'asn',
|
|
||||||
Created = 'created',
|
|
||||||
}
|
|
||||||
|
|
||||||
export enum OcrZoneTransform {
|
|
||||||
None = 'none',
|
|
||||||
Strip = 'strip',
|
|
||||||
Uppercase = 'uppercase',
|
|
||||||
Lowercase = 'lowercase',
|
|
||||||
Numeric = 'numeric',
|
|
||||||
StripPunctuation = 'strip_punctuation',
|
|
||||||
Date = 'date',
|
|
||||||
QrCode = 'qr_code',
|
|
||||||
}
|
|
||||||
|
|
||||||
export const DEFAULT_OCR_ZONE_LANGUAGE = 'eng'
|
|
||||||
|
|
||||||
/** The field a zone writes to, keyed by OcrTemplate.combine_formats. */
|
|
||||||
export function getZoneFieldKey(zone: OcrTemplateZone): string | null {
|
|
||||||
if (zone.target !== OcrZoneTarget.CustomField) return zone.target
|
|
||||||
return zone.custom_field === null ? null : String(zone.custom_field)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Custom field types zone OCR can write to. See models.py OCR_SUPPORTED_FIELD_TYPES. */
|
|
||||||
export const OCR_SUPPORTED_FIELD_TYPES: CustomFieldDataType[] = [
|
|
||||||
CustomFieldDataType.String,
|
|
||||||
CustomFieldDataType.Url,
|
|
||||||
CustomFieldDataType.Date,
|
|
||||||
CustomFieldDataType.Integer,
|
|
||||||
CustomFieldDataType.Float,
|
|
||||||
CustomFieldDataType.Monetary,
|
|
||||||
CustomFieldDataType.LongText,
|
|
||||||
CustomFieldDataType.Boolean,
|
|
||||||
]
|
|
||||||
|
|
||||||
export const OCR_BUILTIN_TARGETS = [
|
|
||||||
{ id: OcrZoneTarget.Title, name: $localize`Title` },
|
|
||||||
{ id: OcrZoneTarget.Asn, name: $localize`Archive serial number` },
|
|
||||||
{ id: OcrZoneTarget.Created, name: $localize`Date created` },
|
|
||||||
]
|
|
||||||
|
|
||||||
export interface OcrTemplateZone {
|
|
||||||
id?: number
|
|
||||||
name: string
|
|
||||||
target: OcrZoneTarget
|
|
||||||
custom_field: number | null
|
|
||||||
page?: number
|
|
||||||
x: number
|
|
||||||
y: number
|
|
||||||
width: number
|
|
||||||
height: number
|
|
||||||
ocr_language: string
|
|
||||||
transform: OcrZoneTransform
|
|
||||||
date_format?: string
|
|
||||||
validation_regex: string
|
|
||||||
order: number
|
|
||||||
zone_source_width?: number
|
|
||||||
zone_source_height?: number
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface OcrTemplate extends MatchingModel, ObjectWithPermissions {
|
|
||||||
name: string
|
|
||||||
sample_document: number | null
|
|
||||||
source_width: number
|
|
||||||
source_height: number
|
|
||||||
enabled: boolean
|
|
||||||
combine_formats?: Record<string, string>
|
|
||||||
created?: string
|
|
||||||
updated?: string
|
|
||||||
zones: OcrTemplateZone[]
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ZoneTestRequest {
|
|
||||||
name: string
|
|
||||||
x: number
|
|
||||||
y: number
|
|
||||||
width: number
|
|
||||||
height: number
|
|
||||||
page: number
|
|
||||||
ocr_language: string
|
|
||||||
transform: OcrZoneTransform
|
|
||||||
date_format?: string
|
|
||||||
validation_regex: string
|
|
||||||
zone_source_width?: number
|
|
||||||
zone_source_height?: number
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface OcrZoneTestResult {
|
|
||||||
raw_text?: string | null
|
|
||||||
value?: string | null
|
|
||||||
regex?: string
|
|
||||||
regex_match?: boolean | null
|
|
||||||
error?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export type OcrZoneRunResponse =
|
|
||||||
| { result: 'OK'; task_id: string }
|
|
||||||
| { result: 'skipped'; reason: 'no_template' }
|
|
||||||
@@ -35,7 +35,6 @@ export enum HideableSidebarItemID {
|
|||||||
SavedViews = 'saved_views',
|
SavedViews = 'saved_views',
|
||||||
ShareLinks = 'share_links',
|
ShareLinks = 'share_links',
|
||||||
Workflows = 'workflows',
|
Workflows = 'workflows',
|
||||||
OcrTemplates = 'ocr_templates',
|
|
||||||
Mail = 'mail',
|
Mail = 'mail',
|
||||||
Documentation = 'documentation',
|
Documentation = 'documentation',
|
||||||
}
|
}
|
||||||
@@ -76,7 +75,6 @@ export const SETTINGS_KEYS = {
|
|||||||
UPDATE_CHECKING_ENABLED: 'general-settings:update-checking:enabled',
|
UPDATE_CHECKING_ENABLED: 'general-settings:update-checking:enabled',
|
||||||
UPDATE_CHECKING_BACKEND_SETTING:
|
UPDATE_CHECKING_BACKEND_SETTING:
|
||||||
'general-settings: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:
|
SAVED_VIEWS_WARN_ON_UNSAVED_CHANGE:
|
||||||
'general-settings:saved-views:warn-on-unsaved-change',
|
'general-settings:saved-views:warn-on-unsaved-change',
|
||||||
DASHBOARD_VIEWS_VISIBLE_IDS:
|
DASHBOARD_VIEWS_VISIBLE_IDS:
|
||||||
@@ -96,7 +94,6 @@ export const SETTINGS_KEYS = {
|
|||||||
DEFAULT_PERMS_VIEW_GROUPS: 'general-settings:permissions:default-view-groups',
|
DEFAULT_PERMS_VIEW_GROUPS: 'general-settings:permissions:default-view-groups',
|
||||||
DEFAULT_PERMS_EDIT_USERS: 'general-settings:permissions:default-edit-users',
|
DEFAULT_PERMS_EDIT_USERS: 'general-settings:permissions:default-edit-users',
|
||||||
DEFAULT_PERMS_EDIT_GROUPS: 'general-settings:permissions:default-edit-groups',
|
DEFAULT_PERMS_EDIT_GROUPS: 'general-settings:permissions:default-edit-groups',
|
||||||
TAGS_SHOW_HIERARCHY: 'general-settings:tags:show-hierarchy',
|
|
||||||
DOCUMENT_EDITING_REMOVE_INBOX_TAGS:
|
DOCUMENT_EDITING_REMOVE_INBOX_TAGS:
|
||||||
'general-settings:document-editing:remove-inbox-tags',
|
'general-settings:document-editing:remove-inbox-tags',
|
||||||
DOCUMENT_EDITING_OVERLAY_THUMBNAIL:
|
DOCUMENT_EDITING_OVERLAY_THUMBNAIL:
|
||||||
@@ -226,11 +223,6 @@ export const SETTINGS: UiSetting[] = [
|
|||||||
type: 'string',
|
type: 'string',
|
||||||
default: '',
|
default: '',
|
||||||
},
|
},
|
||||||
{
|
|
||||||
key: SETTINGS_KEYS.WHATS_NEW_LAST_SEEN_VERSION,
|
|
||||||
type: 'string',
|
|
||||||
default: '',
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
key: SETTINGS_KEYS.SAVED_VIEWS_WARN_ON_UNSAVED_CHANGE,
|
key: SETTINGS_KEYS.SAVED_VIEWS_WARN_ON_UNSAVED_CHANGE,
|
||||||
type: 'boolean',
|
type: 'boolean',
|
||||||
@@ -313,11 +305,6 @@ export const SETTINGS: UiSetting[] = [
|
|||||||
type: 'string',
|
type: 'string',
|
||||||
default: '',
|
default: '',
|
||||||
},
|
},
|
||||||
{
|
|
||||||
key: SETTINGS_KEYS.TAGS_SHOW_HIERARCHY,
|
|
||||||
type: 'boolean',
|
|
||||||
default: true,
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
key: SETTINGS_KEYS.DOCUMENT_EDITING_REMOVE_INBOX_TAGS,
|
key: SETTINGS_KEYS.DOCUMENT_EDITING_REMOVE_INBOX_TAGS,
|
||||||
type: 'boolean',
|
type: 'boolean',
|
||||||
|
|||||||
@@ -3,16 +3,12 @@ import { NgbModal } from '@ng-bootstrap/ng-bootstrap'
|
|||||||
import { DirtyCheckGuard } from '@ngneat/dirty-check-forms'
|
import { DirtyCheckGuard } from '@ngneat/dirty-check-forms'
|
||||||
import { Observable, Subject } from 'rxjs'
|
import { Observable, Subject } from 'rxjs'
|
||||||
import { ConfirmDialogComponent } from 'src/app/components/common/confirm-dialog/confirm-dialog.component'
|
import { ConfirmDialogComponent } from 'src/app/components/common/confirm-dialog/confirm-dialog.component'
|
||||||
import { ActivatedRouteSnapshot } from '@angular/router'
|
|
||||||
|
|
||||||
@Injectable({ providedIn: 'root' })
|
@Injectable({ providedIn: 'root' })
|
||||||
export class DirtyFormGuard extends DirtyCheckGuard {
|
export class DirtyFormGuard extends DirtyCheckGuard {
|
||||||
private modalService = inject(NgbModal)
|
private modalService = inject(NgbModal)
|
||||||
|
|
||||||
confirmChanges(
|
confirmChanges(): Observable<boolean> {
|
||||||
_currentRoute?: ActivatedRouteSnapshot,
|
|
||||||
leaveLabel: string = $localize`Leave page`
|
|
||||||
): Observable<boolean> {
|
|
||||||
let modal = this.modalService.open(ConfirmDialogComponent, {
|
let modal = this.modalService.open(ConfirmDialogComponent, {
|
||||||
backdrop: 'static',
|
backdrop: 'static',
|
||||||
})
|
})
|
||||||
@@ -20,7 +16,7 @@ export class DirtyFormGuard extends DirtyCheckGuard {
|
|||||||
modal.componentInstance.messageBold = $localize`You have unsaved changes.`
|
modal.componentInstance.messageBold = $localize`You have unsaved changes.`
|
||||||
modal.componentInstance.message = $localize`Are you sure you want to leave?`
|
modal.componentInstance.message = $localize`Are you sure you want to leave?`
|
||||||
modal.componentInstance.btnClass = 'btn-warning'
|
modal.componentInstance.btnClass = 'btn-warning'
|
||||||
modal.componentInstance.btnCaption = leaveLabel
|
modal.componentInstance.btnCaption = $localize`Leave page`
|
||||||
modal.componentInstance.confirmClicked.subscribe(() => {
|
modal.componentInstance.confirmClicked.subscribe(() => {
|
||||||
modal.componentInstance.buttonsEnabled.set(false)
|
modal.componentInstance.buttonsEnabled.set(false)
|
||||||
modal.close()
|
modal.close()
|
||||||
|
|||||||
@@ -1,81 +0,0 @@
|
|||||||
import { provideHttpClient, withInterceptorsFromDi } from '@angular/common/http'
|
|
||||||
import { provideHttpClientTesting } from '@angular/common/http/testing'
|
|
||||||
import { TestBed } from '@angular/core/testing'
|
|
||||||
import { firstValueFrom, of, throwError } from 'rxjs'
|
|
||||||
import { Tag } from '../data/tag'
|
|
||||||
import { PermissionsService } from '../services/permissions.service'
|
|
||||||
import { TagService } from '../services/rest/tag.service'
|
|
||||||
import { SettingsService } from '../services/settings.service'
|
|
||||||
import { DisplayTagsPipe } from './display-tags.pipe'
|
|
||||||
|
|
||||||
const tags: Tag[] = [
|
|
||||||
{ id: 1, name: 'Parent' },
|
|
||||||
{ id: 2, name: 'Child', parent: 1 },
|
|
||||||
{ id: 3, name: 'Other' },
|
|
||||||
]
|
|
||||||
|
|
||||||
describe('DisplayTagsPipe', () => {
|
|
||||||
let pipe: DisplayTagsPipe
|
|
||||||
let tagService: TagService
|
|
||||||
let settingsService: SettingsService
|
|
||||||
let permissionsService: PermissionsService
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
TestBed.configureTestingModule({
|
|
||||||
providers: [
|
|
||||||
DisplayTagsPipe,
|
|
||||||
provideHttpClient(withInterceptorsFromDi()),
|
|
||||||
provideHttpClientTesting(),
|
|
||||||
],
|
|
||||||
})
|
|
||||||
pipe = TestBed.inject(DisplayTagsPipe)
|
|
||||||
tagService = TestBed.inject(TagService)
|
|
||||||
settingsService = TestBed.inject(SettingsService)
|
|
||||||
permissionsService = TestBed.inject(PermissionsService)
|
|
||||||
jest.spyOn(permissionsService, 'currentUserCan').mockReturnValue(true)
|
|
||||||
jest.spyOn(settingsService, 'get').mockReturnValue(true)
|
|
||||||
jest
|
|
||||||
.spyOn(tagService, 'listAll')
|
|
||||||
.mockReturnValue(of({ count: 3, all: [1, 2, 3], results: tags }))
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should split visible and hidden tags, collapsing implied parents', async () => {
|
|
||||||
expect(await firstValueFrom(pipe.transform([1, 2, 98, 3]))).toEqual({
|
|
||||||
visible: [2, 3],
|
|
||||||
hidden: [98],
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should not collapse parents when hierarchy display is off', async () => {
|
|
||||||
jest.spyOn(settingsService, 'get').mockReturnValue(false)
|
|
||||||
expect(await firstValueFrom(pipe.transform([1, 2]))).toEqual({
|
|
||||||
visible: [1, 2],
|
|
||||||
hidden: [],
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should hide all tags without tag view permission', async () => {
|
|
||||||
jest.spyOn(permissionsService, 'currentUserCan').mockReturnValue(false)
|
|
||||||
expect(await firstValueFrom(pipe.transform([1, 2]))).toEqual({
|
|
||||||
visible: [],
|
|
||||||
hidden: [1, 2],
|
|
||||||
})
|
|
||||||
expect(tagService.listAll).not.toHaveBeenCalled()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should handle empty input', async () => {
|
|
||||||
const empty = { visible: [], hidden: [] }
|
|
||||||
expect(await firstValueFrom(pipe.transform(null))).toEqual(empty)
|
|
||||||
expect(await firstValueFrom(pipe.transform([]))).toEqual(empty)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('should show the original ids if tags fail to load', async () => {
|
|
||||||
jest
|
|
||||||
.spyOn(tagService, 'listAll')
|
|
||||||
.mockReturnValue(throwError(() => new Error('failed')))
|
|
||||||
expect(await firstValueFrom(pipe.transform([1, 2]))).toEqual({
|
|
||||||
visible: [1, 2],
|
|
||||||
hidden: [],
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
Loaded 100 of 302 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user