mirror of
https://github.com/paperless-ngx/paperless-ngx.git
synced 2026-08-15 15:23:19 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bca2f31c42 | ||
|
|
9541ea2e64 | ||
|
|
fe5d694aeb | ||
|
|
d37c31ed36 | ||
|
|
3322c92837 | ||
|
|
db15c82804 | ||
|
|
fe5d09a123 | ||
|
|
a0feb827c9 | ||
|
|
b599b13f72 |
@@ -1,428 +0,0 @@
|
||||
# Split views.py and serialisers.py Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Split `src/documents/views.py` (5,395 lines) and `src/documents/serialisers.py` (3,532 lines) into domain-based module packages, with zero behavior change.
|
||||
|
||||
**Architecture:** Both files become packages (`documents/views/`, `documents/serialisers/`), one module per domain area. Serialisers split first (views depend on serialisers, never the reverse), then views, then the three external call sites (`paperless/urls.py`, `paperless_mail/views.py`, `paperless_mail/serialisers.py`) are pointed at the new submodules. No `__init__.py` re-exports in either package — every internal and external consumer imports the exact submodule.
|
||||
|
||||
**Tech Stack:** Django REST Framework (viewsets/serializers), ruff (lint/format), pytest via the project's VM test runner.
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-08-13-views-serialisers-split-design.md`
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- No behavior change: class/function bodies, names, and public API responses are unchanged — pure move/reorganize. (spec: Non-goals)
|
||||
- Domain module names are identical across both packages (`bulk_edit.py` exists in both, etc.). (spec: Import direction)
|
||||
- Import direction is one-way: `documents/views/*` may import from `documents/serialisers/*`; `documents/serialisers/*` must never import from `documents/views/*`. (spec: Import direction)
|
||||
- Neither package's `__init__.py` re-exports submodule contents — every consumer, internal or external, imports the specific submodule (e.g. `from documents.views.workflows import WorkflowViewSet`). (spec: Architecture)
|
||||
- `src/documents/tests/test_views.py` and `src/documents/tests/test_api_documents.py` are not modified — they must pass unchanged, proving the move didn't alter behavior. (spec: Non-goals, Testing)
|
||||
- This branch targets `dev` and is separate from `feature-ai-taxonomy-hints-v2`. (spec: Non-goals)
|
||||
- Backend tests run on the Linux VM via the helper script, never locally: `bash /c/Users/tholmes/Documents/Coding/paperless/vmtest.sh "<pytest targets>"`. `ruff check` / `ruff format` run locally (global binary, not `uv run ruff`).
|
||||
|
||||
---
|
||||
|
||||
## Reference: symbol-to-module maps
|
||||
|
||||
These tables (from the spec) are the authoritative source for which class/function goes to which new file. Copy them exactly — do not improvise groupings.
|
||||
|
||||
### `documents/serialisers/` map
|
||||
|
||||
| Module | Symbols |
|
||||
| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `base.py` | `DynamicFieldsModelSerializer`, `DocumentUpdateFieldsModelSerializer`, `MatchingModelSerializer`, `SetPermissionsMixin`, `SerializerWithPerms`, `SetPermissionsSerializer`, `OwnedObjectSerializer`, `OwnedObjectListSerializer`, `ReadWriteSerializerMethodField`, `DocumentListSerializer`, `DocumentSelectionSerializer`, `SourceModeValidationMixin`, `BasicUserSerializer`, `NotesSerializer` |
|
||||
| `metadata.py` | `CorrespondentSerializer`, `DocumentTypeSerializer`, `DeprecatedColors`, `ColorField`, `TagSerializer`, `CorrespondentField`, `TagsField`, `DocumentTypeField`, `StoragePathField`, `StoragePathSerializer`, `StoragePathTestSerializer`, `CustomFieldSerializer`, `CustomFieldInstanceSerializer`, `validate_documentlink_targets` |
|
||||
| `documents.py` | `DocumentSerializer`, `SearchResultListSerializer`, `SearchResultSerializer`, `DuplicateDocumentSummarySerializer`, `_DocumentVersionInfo`, `DocumentVersionInfoSerializer`, `DocumentVersionSerializer`, `DocumentVersionLabelSerializer`, `_get_viewable_duplicates` |
|
||||
| `upload.py` | `PostDocumentSerializer` |
|
||||
| `saved_views.py` | `SavedViewFilterRuleSerializer`, `SavedViewSerializer` |
|
||||
| `bulk_edit.py` | `RotateDocumentsSerializer`, `MergeDocumentsSerializer`, `EditPdfDocumentsSerializer`, `RemovePasswordDocumentsSerializer`, `DeleteDocumentsSerializer`, `ReprocessDocumentsSerializer`, `BulkEditSerializer`, `BulkDownloadSerializer`, `BulkEditObjectsSerializer` |
|
||||
| `sharing.py` | `EmailSerializer`, `ShareLinkSerializer`, `ShareLinkBundleSerializer` |
|
||||
| `tasks.py` | `TaskSerializerV10`, `TaskSerializerV9`, `TaskSummarySerializer`, `RunTaskSerializer`, `AcknowledgeTasksViewSerializer` |
|
||||
| `workflows.py` | `WorkflowTriggerSerializer`, `WorkflowActionEmailSerializer`, `WorkflowActionWebhookSerializer`, `WorkflowActionSerializer`, `WorkflowSerializer` |
|
||||
| `system.py` | `UiSettingsViewSerializer`, `TrashSerializer` |
|
||||
|
||||
Extraction order matters (later modules reference earlier ones): `base` → `metadata` → `documents` → `upload` → `saved_views` → `bulk_edit` → `sharing` → `tasks` → `workflows` → `system`.
|
||||
|
||||
### `documents/views/` map
|
||||
|
||||
| Module | Symbols |
|
||||
| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `base.py` | `PassUserMixin`, `BulkPermissionMixin`, `PermissionsAwareDocumentCountMixin`, `DocumentSelectionMixin`, `DocumentOperationPermissionMixin`, `SearchParams`, `SearchResultPage`, `ResolvedRequestDocs`, `_get_tantivy_query_and_mode`, `_get_more_like_id`, `serve_file` |
|
||||
| `index.py` | `IndexView`, `serve_logo` |
|
||||
| `metadata.py` | `CorrespondentViewSet`, `TagViewSet`, `DocumentTypeViewSet`, `StoragePathViewSet`, `CustomFieldViewSet`, `_get_llm_output_language` |
|
||||
| `documents.py` | `EmailDocumentDetailSchema`, `DocumentViewSet`, `UnifiedSearchViewSet` |
|
||||
| `upload.py` | `PostDocumentView` |
|
||||
| `chat.py` | `ChatStreamingSerializer`, `ChatStreamingView` |
|
||||
| `search.py` | `SearchAutoCompleteView`, `GlobalSearchView`, `SelectionDataView`, `StatisticsView` |
|
||||
| `bulk_edit.py` | `BulkEditView`, `RotateDocumentsView`, `MergeDocumentsView`, `DeleteDocumentsView`, `ReprocessDocumentsView`, `EditPdfDocumentsView`, `RemovePasswordDocumentsView`, `BulkEditObjectsView`, `BulkDownloadView` |
|
||||
| `sharing.py` | `ShareLinkViewSet`, `ShareLinkBundleViewSet`, `SharedLinkView` |
|
||||
| `saved_views.py` | `SavedViewViewSet` |
|
||||
| `tasks.py` | `_TasksViewSetSchema`, `TasksViewSet` |
|
||||
| `workflows.py` | `WorkflowTriggerViewSet`, `WorkflowActionViewSet`, `WorkflowViewSet` |
|
||||
| `system.py` | `UiSettingsView`, `RemoteVersionView`, `SystemStatusView`, `TrashView` |
|
||||
| `logs.py` | `LogViewSet` |
|
||||
|
||||
Extraction order: `base` → `index` → `metadata` → `documents` → `upload` → `chat` → `search` → `bulk_edit` → `sharing` → `saved_views` → `tasks` → `workflows` → `system` → `logs`. Note `ChatStreamingSerializer` is defined in `views.py` today, directly above `ChatStreamingView` — it moves with it into `views/chat.py`, not into the serialisers package.
|
||||
|
||||
### Mechanical extraction recipe (applies to every task below)
|
||||
|
||||
For each module being created:
|
||||
|
||||
1. `grep -n "^class |^def " src/documents/<serialisers|views>.py` to get current line numbers for every symbol still in the monolith (numbers shift as earlier modules are extracted, so re-run this each time, don't reuse stale numbers).
|
||||
2. Create the new file. Start it by copying the **entire top-of-file import block** from the monolith verbatim, plus a relative `from .base import ...` line if the module isn't `base.py` itself.
|
||||
3. Cut each listed symbol (including any decorators/comments immediately above it) from the monolith and paste it into the new file, preserving original order.
|
||||
4. Remove the cut symbols from the monolith.
|
||||
5. Run `ruff check --select F401,F811,F821 <new file> <monolith file>` and fix everything reported:
|
||||
- `F401` (unused import) → delete the import line.
|
||||
- `F821` (undefined name) → the symbol lives in a sibling module already extracted; add `from .<sibling> import <Symbol>`. If it hasn't been extracted yet, that's an ordering bug — stop and re-check the extraction order table.
|
||||
- `F811` (redefinition) → duplicate import, delete one.
|
||||
6. Run `ruff format <new file> <monolith file>`.
|
||||
|
||||
## Task 1: Scaffold `documents/serialisers/` and extract `base.py`
|
||||
|
||||
**Agent:** django-expert — **Model:** sonnet (mechanical extraction, but sets the foundation every later serialiser module imports from — get the base set right or every later task inherits the mistake)
|
||||
|
||||
**Files:**
|
||||
|
||||
- Create: `src/documents/serialisers/__init__.py` (empty — no re-exports, per Global Constraints)
|
||||
- Create: `src/documents/serialisers/base.py`
|
||||
- Modify: `src/documents/serialisers.py` (shrinks; stays in place as the monolith for the remaining tasks in this phase — it is only deleted in Task 2 once empty)
|
||||
- Test: `src/documents/tests/` (full app suite), `src/paperless_mail/tests/`
|
||||
|
||||
**Interfaces:**
|
||||
|
||||
- Produces: `documents.serialisers.base` exporting `DynamicFieldsModelSerializer`, `DocumentUpdateFieldsModelSerializer`, `MatchingModelSerializer`, `SetPermissionsMixin`, `SerializerWithPerms`, `SetPermissionsSerializer`, `OwnedObjectSerializer`, `OwnedObjectListSerializer`, `ReadWriteSerializerMethodField`, `DocumentListSerializer`, `DocumentSelectionSerializer`, `SourceModeValidationMixin`, `BasicUserSerializer`, `NotesSerializer` — every later serialiser/view module that needs one of these imports `from documents.serialisers.base import <Symbol>`.
|
||||
|
||||
- [ ] **Step 1: Create the package directory and empty `__init__.py`**
|
||||
|
||||
```bash
|
||||
mkdir -p src/documents/serialisers
|
||||
touch src/documents/serialisers/__init__.py
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Extract `base.py` per the mechanical extraction recipe above**
|
||||
|
||||
Move exactly these 14 symbols (in their current relative order) out of `src/documents/serialisers.py` into `src/documents/serialisers/base.py`: `DynamicFieldsModelSerializer`, `DocumentUpdateFieldsModelSerializer`, `MatchingModelSerializer`, `SetPermissionsMixin`, `SerializerWithPerms`, `SetPermissionsSerializer`, `OwnedObjectSerializer`, `OwnedObjectListSerializer`, `ReadWriteSerializerMethodField`, `DocumentListSerializer`, `DocumentSelectionSerializer`, `SourceModeValidationMixin`, `BasicUserSerializer`, `NotesSerializer`.
|
||||
|
||||
Run the ruff fix-up (`ruff check --select F401,F811,F821 src/documents/serialisers/base.py src/documents/serialisers.py` then `ruff format` both files) as described in the recipe.
|
||||
|
||||
- [ ] **Step 3: Verify `documents.serialisers` (the monolith module, still at `src/documents/serialisers.py`) still imports cleanly and the app still boots**
|
||||
|
||||
Note: at this point Python resolves `documents.serialisers` to the package `src/documents/serialisers/__init__.py` (empty), **not** to `src/documents/serialisers.py` — having both a `serialisers.py` file and a `serialisers/` directory in the same parent package is invalid and Python will pick the package. So before running anything, rename the monolith out of the way so it's importable as a submodule of the new package for the rest of Phase A:
|
||||
|
||||
```bash
|
||||
git mv src/documents/serialisers.py src/documents/serialisers/_monolith.py
|
||||
```
|
||||
|
||||
Everywhere else in this phase, "the monolith file" now means `src/documents/serialisers/_monolith.py`. Because nothing outside this package imports the monolith directly by its old dotted path (`documents.serialisers` resolved to the file before; now it's the package), you must update every consumer of `documents.serialisers` symbols still owned by the monolith to import from `documents.serialisers._monolith` for the remainder of this phase. Concretely, in `src/documents/views.py`, change every `from documents.serialisers import <Symbol>` line for a symbol _not yet extracted_ (i.e., not one of the 14 `base.py` symbols) to `from documents.serialisers._monolith import <Symbol>`, and change the 14 now-extracted symbols' import lines to `from documents.serialisers.base import <Symbol>`. Do the same in `src/paperless_mail/serialisers.py` for `OwnedObjectSerializer` (→ `documents.serialisers.base`); its other three imports (`CorrespondentField`, `DocumentTypeField`, `TagsField`) stay pointed at `documents.serialisers._monolith` until Task 2 moves them into `metadata.py`.
|
||||
|
||||
This `_monolith` re-pointing is scaffolding only — Task 2 finishes emptying and deletes `_monolith.py`, and every import that currently says `._monolith` gets its final home then.
|
||||
|
||||
- [ ] **Step 4: Run the full test suite for this app boundary**
|
||||
|
||||
```bash
|
||||
bash /c/Users/tholmes/Documents/Coding/paperless/vmtest.sh "src/documents/tests src/paperless_mail/tests -v"
|
||||
```
|
||||
|
||||
Expected: PASS, no collection errors (a collection error here almost always means a missed import update in `views.py` or `paperless_mail/serialisers.py`).
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add src/documents/serialisers src/documents/views.py src/paperless_mail/serialisers.py
|
||||
git commit -m "refactor: extract documents/serialisers/base.py from the serialisers monolith"
|
||||
```
|
||||
|
||||
## Task 2: Extract the remaining 8 serialiser domain modules and delete the monolith
|
||||
|
||||
**Agent:** django-expert — **Model:** sonnet (repetitive but each of the 8 modules needs its own cross-reference check against `base.py` and previously-extracted siblings; DocumentSerializer in particular is large and central)
|
||||
|
||||
**Files:**
|
||||
|
||||
- Create: `src/documents/serialisers/metadata.py`, `src/documents/serialisers/documents.py`, `src/documents/serialisers/upload.py`, `src/documents/serialisers/saved_views.py`, `src/documents/serialisers/bulk_edit.py`, `src/documents/serialisers/sharing.py`, `src/documents/serialisers/tasks.py`, `src/documents/serialisers/workflows.py`, `src/documents/serialisers/system.py`
|
||||
- Delete: `src/documents/serialisers/_monolith.py` (once empty)
|
||||
- Modify: `src/documents/views.py` (finish re-pointing every `from documents.serialisers._monolith import X` line at the correct new submodule), `src/paperless_mail/serialisers.py` (re-point `CorrespondentField`, `DocumentTypeField`, `TagsField` at `documents.serialisers.metadata`)
|
||||
- Test: `src/documents/tests/` (full app suite), `src/paperless_mail/tests/`
|
||||
|
||||
**Interfaces:**
|
||||
|
||||
- Consumes: `documents.serialisers.base` from Task 1 (relative import `.base` within the package).
|
||||
- Produces: the full `documents/serialisers/` package as specified in the Reference map above — this is what Task 3/4 (views split) and Task 5 (external call sites) import from.
|
||||
|
||||
- [ ] **Step 1: Extract the 8 remaining domain modules in order**
|
||||
|
||||
Following the mechanical extraction recipe, and in this exact order (each may depend on symbols extracted earlier in this same order, plus anything in `base.py`):
|
||||
|
||||
1. `metadata.py` — `CorrespondentSerializer`, `DocumentTypeSerializer`, `DeprecatedColors`, `ColorField`, `TagSerializer`, `CorrespondentField`, `TagsField`, `DocumentTypeField`, `StoragePathField`, `StoragePathSerializer`, `StoragePathTestSerializer`, `CustomFieldSerializer`, `CustomFieldInstanceSerializer`, `validate_documentlink_targets`
|
||||
2. `documents.py` — `DocumentSerializer`, `SearchResultListSerializer`, `SearchResultSerializer`, `DuplicateDocumentSummarySerializer`, `_DocumentVersionInfo`, `DocumentVersionInfoSerializer`, `DocumentVersionSerializer`, `DocumentVersionLabelSerializer`, `_get_viewable_duplicates`
|
||||
3. `upload.py` — `PostDocumentSerializer`
|
||||
4. `saved_views.py` — `SavedViewFilterRuleSerializer`, `SavedViewSerializer`
|
||||
5. `bulk_edit.py` — `RotateDocumentsSerializer`, `MergeDocumentsSerializer`, `EditPdfDocumentsSerializer`, `RemovePasswordDocumentsSerializer`, `DeleteDocumentsSerializer`, `ReprocessDocumentsSerializer`, `BulkEditSerializer`, `BulkDownloadSerializer`, `BulkEditObjectsSerializer`
|
||||
6. `sharing.py` — `EmailSerializer`, `ShareLinkSerializer`, `ShareLinkBundleSerializer`
|
||||
7. `tasks.py` — `TaskSerializerV10`, `TaskSerializerV9`, `TaskSummarySerializer`, `RunTaskSerializer`, `AcknowledgeTasksViewSerializer`
|
||||
8. `workflows.py` — `WorkflowTriggerSerializer`, `WorkflowActionEmailSerializer`, `WorkflowActionWebhookSerializer`, `WorkflowActionSerializer`, `WorkflowSerializer`
|
||||
9. `system.py` — `UiSettingsViewSerializer`, `TrashSerializer`
|
||||
|
||||
After each individual module extraction, run the ruff fix-up from the recipe against that new file and `_monolith.py` before moving to the next module (don't batch all 8 and fix imports once at the end — F821 errors compound and get harder to attribute to the right module).
|
||||
|
||||
- [ ] **Step 2: Confirm the monolith is empty and delete it**
|
||||
|
||||
```bash
|
||||
grep -n "^class |^def " src/documents/serialisers/_monolith.py
|
||||
```
|
||||
|
||||
Expected: no output. If anything remains, it wasn't in the Reference map — stop and reconcile with the spec rather than deleting a symbol.
|
||||
|
||||
```bash
|
||||
git rm src/documents/serialisers/_monolith.py
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Re-point every remaining `._monolith` import**
|
||||
|
||||
Search for any import left pointing at the now-deleted module:
|
||||
|
||||
```bash
|
||||
grep -rn "serialisers\._monolith\|serialisers/_monolith" src/
|
||||
```
|
||||
|
||||
Expected: no output. Fix any that remain by pointing them at the correct submodule per the Reference map (e.g. `from documents.serialisers._monolith import DocumentSerializer` → `from documents.serialisers.documents import DocumentSerializer`).
|
||||
|
||||
- [ ] **Step 4: Update `paperless_mail/serialisers.py`'s remaining imports**
|
||||
|
||||
```python
|
||||
# was: from documents.serialisers import CorrespondentField, DocumentTypeField, OwnedObjectSerializer, TagsField
|
||||
from documents.serialisers.base import OwnedObjectSerializer
|
||||
from documents.serialisers.metadata import CorrespondentField, DocumentTypeField, TagsField
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Ruff and full test suite**
|
||||
|
||||
```bash
|
||||
ruff check src/documents/serialisers src/documents/views.py src/paperless_mail/serialisers.py
|
||||
ruff format src/documents/serialisers src/documents/views.py src/paperless_mail/serialisers.py
|
||||
```
|
||||
|
||||
```bash
|
||||
bash /c/Users/tholmes/Documents/Coding/paperless/vmtest.sh "src/documents/tests src/paperless_mail/tests -v"
|
||||
```
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 6: Commit**
|
||||
|
||||
```bash
|
||||
git add src/documents/serialisers src/documents/views.py src/paperless_mail/serialisers.py
|
||||
git commit -m "refactor: finish splitting serialisers.py into documents/serialisers/"
|
||||
```
|
||||
|
||||
## Task 3: Scaffold `documents/views/` and extract `base.py`
|
||||
|
||||
**Agent:** django-expert — **Model:** sonnet (same shape as Task 1, one level up — views/base.py is imported by every other view module)
|
||||
|
||||
**Files:**
|
||||
|
||||
- Create: `src/documents/views/__init__.py` (empty), `src/documents/views/base.py`
|
||||
- Modify: `src/documents/views.py` → `src/documents/views/_monolith.py` (renamed, same reasoning as Task 1 Step 3)
|
||||
- Modify: `src/paperless/urls.py`, `src/paperless_mail/views.py` (re-point the 1 symbol each currently pulls from `documents.views` that now lives in `base.py`, if any — see step 3)
|
||||
- Test: `src/documents/tests/` (full app suite, includes URL-resolution-dependent tests), `src/paperless_mail/tests/`
|
||||
|
||||
**Interfaces:**
|
||||
|
||||
- Consumes: `documents.serialisers.*` submodules from Tasks 1–2 (already at final locations — import these directly, e.g. `from documents.serialisers.documents import DocumentSerializer`, never through a monolith or shim).
|
||||
- Produces: `documents.views.base` exporting `PassUserMixin`, `BulkPermissionMixin`, `PermissionsAwareDocumentCountMixin`, `DocumentSelectionMixin`, `DocumentOperationPermissionMixin`, `SearchParams`, `SearchResultPage`, `ResolvedRequestDocs`, `_get_tantivy_query_and_mode`, `_get_more_like_id`, `serve_file`.
|
||||
|
||||
- [ ] **Step 1: Create the package directory, empty `__init__.py`, and rename the monolith**
|
||||
|
||||
```bash
|
||||
mkdir -p src/documents/views
|
||||
touch src/documents/views/__init__.py
|
||||
git mv src/documents/views.py src/documents/views/_monolith.py
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Extract `base.py` per the mechanical extraction recipe**
|
||||
|
||||
Move exactly these 11 symbols out of `_monolith.py` into `views/base.py`: `PassUserMixin`, `BulkPermissionMixin`, `PermissionsAwareDocumentCountMixin`, `DocumentSelectionMixin`, `DocumentOperationPermissionMixin`, `SearchParams`, `SearchResultPage`, `ResolvedRequestDocs`, `_get_tantivy_query_and_mode`, `_get_more_like_id`, `serve_file`.
|
||||
|
||||
Within `_monolith.py`, every reference to these 11 symbols needs `from .base import <Symbol>` added (they're used throughout the rest of the file by the not-yet-extracted viewsets).
|
||||
|
||||
- [ ] **Step 3: Re-point external consumers of the now-moved symbol**
|
||||
|
||||
```bash
|
||||
grep -n "from documents.views import PassUserMixin" src/paperless_mail/views.py
|
||||
```
|
||||
|
||||
Update it to `from documents.views.base import PassUserMixin`.
|
||||
|
||||
`paperless/urls.py` doesn't import any of the 11 `base.py` symbols directly (it only imports viewsets/views, which are all still in `_monolith.py` at this point) — confirm with:
|
||||
|
||||
```bash
|
||||
grep -nE "from documents\.views import (PassUserMixin|BulkPermissionMixin|PermissionsAwareDocumentCountMixin|DocumentSelectionMixin|DocumentOperationPermissionMixin|serve_file)" src/paperless/urls.py
|
||||
```
|
||||
|
||||
Expected: no output. If something does match, re-point it at `documents.views.base` the same way.
|
||||
|
||||
- [ ] **Step 4: Ruff and test**
|
||||
|
||||
```bash
|
||||
ruff check src/documents/views src/paperless_mail/views.py
|
||||
ruff format src/documents/views src/paperless_mail/views.py
|
||||
bash /c/Users/tholmes/Documents/Coding/paperless/vmtest.sh "src/documents/tests src/paperless_mail/tests -v"
|
||||
```
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add src/documents/views src/paperless_mail/views.py
|
||||
git commit -m "refactor: extract documents/views/base.py from the views monolith"
|
||||
```
|
||||
|
||||
## Task 4: Extract the remaining 13 view domain modules and delete the monolith
|
||||
|
||||
**Agent:** django-expert — **Model:** opus (highest blast radius in the plan — `DocumentViewSet` alone is ~1,300 lines and central to the whole API; this task also rewires `paperless/urls.py`'s ~34 import lines that drive URL routing for the entire backend, where a mistake breaks the app at startup, not just in one test)
|
||||
|
||||
**Files:**
|
||||
|
||||
- Create: `src/documents/views/index.py`, `src/documents/views/metadata.py`, `src/documents/views/documents.py`, `src/documents/views/upload.py`, `src/documents/views/chat.py`, `src/documents/views/search.py`, `src/documents/views/bulk_edit.py`, `src/documents/views/sharing.py`, `src/documents/views/saved_views.py`, `src/documents/views/tasks.py`, `src/documents/views/workflows.py`, `src/documents/views/system.py`, `src/documents/views/logs.py`
|
||||
- Delete: `src/documents/views/_monolith.py` (once empty)
|
||||
- Modify: `src/paperless/urls.py` (all ~34 `from documents.views import X` lines)
|
||||
- Test: `src/documents/tests/` (full app suite — includes `test_views.py`, `test_api_documents.py`), `src/paperless_mail/tests/`
|
||||
|
||||
**Interfaces:**
|
||||
|
||||
- Consumes: `documents.serialisers.*` (Tasks 1–2) and `documents.views.base` (Task 3).
|
||||
- Produces: the full `documents/views/` package as specified in the Reference map above.
|
||||
|
||||
- [ ] **Step 1: Extract the 13 remaining domain modules in order**
|
||||
|
||||
Following the mechanical extraction recipe, in this exact order:
|
||||
|
||||
1. `index.py` — `IndexView`, `serve_logo`
|
||||
2. `metadata.py` — `CorrespondentViewSet`, `TagViewSet`, `DocumentTypeViewSet`, `StoragePathViewSet`, `CustomFieldViewSet`, `_get_llm_output_language`
|
||||
3. `documents.py` — `EmailDocumentDetailSchema`, `DocumentViewSet`, `UnifiedSearchViewSet`
|
||||
4. `upload.py` — `PostDocumentView`
|
||||
5. `chat.py` — `ChatStreamingSerializer`, `ChatStreamingView`
|
||||
6. `search.py` — `SearchAutoCompleteView`, `GlobalSearchView`, `SelectionDataView`, `StatisticsView`
|
||||
7. `bulk_edit.py` — `BulkEditView`, `RotateDocumentsView`, `MergeDocumentsView`, `DeleteDocumentsView`, `ReprocessDocumentsView`, `EditPdfDocumentsView`, `RemovePasswordDocumentsView`, `BulkEditObjectsView`, `BulkDownloadView`
|
||||
8. `sharing.py` — `ShareLinkViewSet`, `ShareLinkBundleViewSet`, `SharedLinkView`
|
||||
9. `saved_views.py` — `SavedViewViewSet`
|
||||
10. `tasks.py` — `_TasksViewSetSchema`, `TasksViewSet`
|
||||
11. `workflows.py` — `WorkflowTriggerViewSet`, `WorkflowActionViewSet`, `WorkflowViewSet`
|
||||
12. `system.py` — `UiSettingsView`, `RemoteVersionView`, `SystemStatusView`, `TrashView`
|
||||
13. `logs.py` — `LogViewSet`
|
||||
|
||||
After each module, run the ruff fix-up from the recipe before continuing to the next (same rationale as Task 2 Step 1 — attribute F821s to the right module while context is fresh). `documents.py` is the biggest single extraction in this whole plan (`DocumentViewSet` is ~1,300 lines) — expect the most F821 fix-ups here, mostly resolved by adding `from documents.serialisers.documents import ...`, `from documents.serialisers.metadata import ...`, and `from .base import ...` as needed.
|
||||
|
||||
- [ ] **Step 2: Confirm the monolith is empty and delete it**
|
||||
|
||||
```bash
|
||||
grep -n "^class |^def " src/documents/views/_monolith.py
|
||||
```
|
||||
|
||||
Expected: no output.
|
||||
|
||||
```bash
|
||||
git rm src/documents/views/_monolith.py
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Re-point every remaining `._monolith` import**
|
||||
|
||||
```bash
|
||||
grep -rn "views\._monolith\|views/_monolith" src/
|
||||
```
|
||||
|
||||
Expected: no output. Fix any stragglers per the Reference map.
|
||||
|
||||
- [ ] **Step 4: Update `paperless/urls.py`**
|
||||
|
||||
Replace each of the ~34 `from documents.views import X` lines with `from documents.views.<domain> import X` per the Reference map. For example:
|
||||
|
||||
```python
|
||||
# was:
|
||||
from documents.views import CorrespondentViewSet
|
||||
from documents.views import WorkflowViewSet
|
||||
from documents.views import serve_logo
|
||||
# becomes:
|
||||
from documents.views.metadata import CorrespondentViewSet
|
||||
from documents.views.workflows import WorkflowViewSet
|
||||
from documents.views.index import serve_logo
|
||||
```
|
||||
|
||||
Do this for every import in that block — check off against the full symbol list in the Reference map above so none are missed.
|
||||
|
||||
- [ ] **Step 5: Ruff and test**
|
||||
|
||||
```bash
|
||||
ruff check src/documents/views src/paperless/urls.py
|
||||
ruff format src/documents/views src/paperless/urls.py
|
||||
bash /c/Users/tholmes/Documents/Coding/paperless/vmtest.sh "src/documents/tests src/paperless_mail/tests -v"
|
||||
```
|
||||
|
||||
Expected: PASS, including `test_views.py` and `test_api_documents.py` — these exercise URL routing end-to-end, so a broken `urls.py` import shows up here as a collection error.
|
||||
|
||||
- [ ] **Step 6: Commit**
|
||||
|
||||
```bash
|
||||
git add src/documents/views src/paperless/urls.py
|
||||
git commit -m "refactor: finish splitting views.py into documents/views/"
|
||||
```
|
||||
|
||||
## Task 5: Repo-wide verification sweep
|
||||
|
||||
**Agent:** general-purpose — **Model:** sonnet (an audit/verification pass: run targeted checks, read the output, fix anything found — moderate judgment, not novel design work)
|
||||
|
||||
**Files:**
|
||||
|
||||
- Modify: any file a grep in this task turns up beyond the ones already handled in Tasks 1–4 (expected: none, per the spec's stated blast radius of exactly `paperless/urls.py`, `paperless_mail/views.py`, `paperless_mail/serialisers.py` — this task exists to confirm that, not to find new work)
|
||||
- Test: full backend suite (all apps, not just `documents`/`paperless_mail`)
|
||||
|
||||
**Interfaces:**
|
||||
|
||||
- Consumes: the finished `documents/views/` and `documents/serialisers/` packages from Tasks 1–4.
|
||||
|
||||
- [ ] **Step 1: Grep the whole repo for any remaining bare-module reference**
|
||||
|
||||
```bash
|
||||
grep -rn "from documents\.views import\|from documents\.serialisers import\|documents\.views\.\_monolith\|documents\.serialisers\.\_monolith\|import documents\.views$\|import documents\.serialisers$" src/
|
||||
```
|
||||
|
||||
Expected: no output. `documents/views/__init__.py` and `documents/serialisers/__init__.py` should still be empty (`0` bytes or a single blank line) — confirm with:
|
||||
|
||||
```bash
|
||||
wc -l src/documents/views/__init__.py src/documents/serialisers/__init__.py
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Confirm import direction was never violated**
|
||||
|
||||
```bash
|
||||
grep -rln "from documents\.views" src/documents/serialisers/
|
||||
```
|
||||
|
||||
Expected: no output (no file in `serialisers/` imports from `views/`).
|
||||
|
||||
- [ ] **Step 3: Full ruff pass**
|
||||
|
||||
```bash
|
||||
ruff check src/documents/views src/documents/serialisers src/paperless/urls.py src/paperless_mail/views.py src/paperless_mail/serialisers.py
|
||||
ruff format --check src/documents/views src/documents/serialisers src/paperless/urls.py src/paperless_mail/views.py src/paperless_mail/serialisers.py
|
||||
```
|
||||
|
||||
Expected: clean.
|
||||
|
||||
- [ ] **Step 4: Full backend test suite**
|
||||
|
||||
```bash
|
||||
bash /c/Users/tholmes/Documents/Coding/paperless/vmtest.sh "-v"
|
||||
```
|
||||
|
||||
(No path filter — this runs the whole backend suite, confirming nothing outside `documents`/`paperless_mail` was quietly relying on the old module shape, e.g. a management command or a script under `scripts/`.)
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 5: If Steps 1–4 found nothing to fix, commit is a no-op — skip it. If they found strays, fix and commit**
|
||||
|
||||
```bash
|
||||
git add -A
|
||||
git commit -m "refactor: fix stray documents.views/serialisers references found in repo sweep"
|
||||
```
|
||||
@@ -1,158 +0,0 @@
|
||||
# Split `documents/views.py` and `documents/serialisers.py` into modules
|
||||
|
||||
## Problem
|
||||
|
||||
`src/documents/views.py` (5,395 lines) and `src/documents/serialisers.py`
|
||||
(3,532 lines) have grown into monolithic files covering every REST resource
|
||||
in the `documents` app: correspondents, tags, document types, storage paths,
|
||||
custom fields, the core document viewset and search, chat, bulk-edit
|
||||
operations, sharing, saved views, tasks, workflows, and system/UI settings.
|
||||
Their size makes them hard to navigate, hard to review incrementally, and
|
||||
increases the chance of unrelated changes colliding in the same file.
|
||||
|
||||
This document specifies splitting both files into packages, one module per
|
||||
domain area, with no behavior change.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- No behavior change. Class names, method bodies, and public API responses
|
||||
are unchanged — this is a pure move/reorganize.
|
||||
- No change to `test_views.py` or `test_api_documents.py`. They exercise the
|
||||
moved classes via imports or via the live API; class names and behavior
|
||||
don't change, so they need no edits. Splitting those test files is a
|
||||
separate, later task if desired.
|
||||
- No change to the frontend, migrations, or any other app beyond the three
|
||||
files that import from `documents.views` / `documents.serialisers`
|
||||
(`paperless/urls.py`, `paperless_mail/views.py`,
|
||||
`paperless_mail/serialisers.py`).
|
||||
- This work happens as its own branch/PR against `dev`, after the in-flight
|
||||
`feature-ai-taxonomy-hints-v2` work merges — not layered on top of it.
|
||||
|
||||
## Architecture
|
||||
|
||||
`documents/views.py` becomes the package `documents/views/`, and
|
||||
`documents/serialisers.py` becomes `documents/serialisers/`. Each gets one
|
||||
module per domain area (table below). Neither package's `__init__.py`
|
||||
re-exports its submodules' contents — it stays empty (or a short docstring
|
||||
only). The three external call sites that currently do
|
||||
`from documents.views import X` / `from documents.serialisers import X` are
|
||||
updated to import from the specific submodule instead
|
||||
(`from documents.views.workflows import WorkflowViewSet`, etc.). This avoids
|
||||
adding an indirection layer that could quietly regrow into a second dumping
|
||||
ground, at the cost of touching those three files.
|
||||
|
||||
### Import direction
|
||||
|
||||
`views/*` modules may import from `serialisers/*` modules; `serialisers/*`
|
||||
modules never import from `views/*`. This keeps the dependency graph acyclic
|
||||
by construction — there is no case in the current code where a serializer
|
||||
needs a view.
|
||||
|
||||
Domain module names are the same across both packages (e.g. `bulk_edit.py`
|
||||
exists in both), which makes the natural import `from documents.serialisers.bulk_edit import BulkEditSerializer`
|
||||
inside `documents/views/bulk_edit.py` easy to find, but a view is free to
|
||||
import a serializer from a different domain module when needed (e.g. a
|
||||
`documents.py` view using a `metadata.py` field serializer) — that's a plain
|
||||
cross-module import, not a cycle risk, since the reverse direction never
|
||||
happens.
|
||||
|
||||
## Module breakdown — `documents/views/`
|
||||
|
||||
| Module | Contents |
|
||||
| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `base.py` | Shared mixins/helpers: `PassUserMixin`, `BulkPermissionMixin`, `PermissionsAwareDocumentCountMixin`, `DocumentSelectionMixin`, `DocumentOperationPermissionMixin`, `SearchParams`/`SearchResultPage`/`ResolvedRequestDocs`, `_get_tantivy_query_and_mode`, `_get_more_like_id`, `serve_file` |
|
||||
| `index.py` | `IndexView`, `serve_logo` |
|
||||
| `metadata.py` | `CorrespondentViewSet`, `TagViewSet`, `DocumentTypeViewSet`, `StoragePathViewSet`, `CustomFieldViewSet`, `_get_llm_output_language` |
|
||||
| `documents.py` | `EmailDocumentDetailSchema`, `DocumentViewSet`, `UnifiedSearchViewSet` |
|
||||
| `upload.py` | `PostDocumentView` |
|
||||
| `chat.py` | `ChatStreamingSerializer`, `ChatStreamingView` |
|
||||
| `search.py` | `SearchAutoCompleteView`, `GlobalSearchView`, `SelectionDataView`, `StatisticsView` |
|
||||
| `bulk_edit.py` | `BulkEditView`, `RotateDocumentsView`, `MergeDocumentsView`, `DeleteDocumentsView`, `ReprocessDocumentsView`, `EditPdfDocumentsView`, `RemovePasswordDocumentsView`, `BulkEditObjectsView`, `BulkDownloadView` |
|
||||
| `sharing.py` | `ShareLinkViewSet`, `ShareLinkBundleViewSet`, `SharedLinkView` |
|
||||
| `saved_views.py` | `SavedViewViewSet` |
|
||||
| `tasks.py` | `_TasksViewSetSchema`, `TasksViewSet` |
|
||||
| `workflows.py` | `WorkflowTriggerViewSet`, `WorkflowActionViewSet`, `WorkflowViewSet` |
|
||||
| `system.py` | `UiSettingsView`, `RemoteVersionView`, `SystemStatusView`, `TrashView` |
|
||||
| `logs.py` | `LogViewSet` |
|
||||
|
||||
`documents.py` remains the largest module at roughly 1,600 lines
|
||||
(`DocumentViewSet` alone is ~1,300 lines in the current file); every other
|
||||
module is well under 500 lines.
|
||||
|
||||
## Module breakdown — `documents/serialisers/`
|
||||
|
||||
| Module | Contents |
|
||||
| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `base.py` | `DynamicFieldsModelSerializer`, `DocumentUpdateFieldsModelSerializer`, `MatchingModelSerializer`, `SetPermissionsMixin`, `SerializerWithPerms`, `SetPermissionsSerializer`, `OwnedObjectSerializer`, `OwnedObjectListSerializer`, `ReadWriteSerializerMethodField`, `DocumentListSerializer`, `DocumentSelectionSerializer`, `SourceModeValidationMixin`, `BasicUserSerializer`, `NotesSerializer` |
|
||||
| `metadata.py` | `CorrespondentSerializer`, `DocumentTypeSerializer`, `DeprecatedColors`, `ColorField`, `TagSerializer`, `CorrespondentField`, `TagsField`, `DocumentTypeField`, `StoragePathField`, `StoragePathSerializer`, `StoragePathTestSerializer`, `CustomFieldSerializer`, `CustomFieldInstanceSerializer`, `validate_documentlink_targets` |
|
||||
| `documents.py` | `DocumentSerializer`, `SearchResultListSerializer`, `SearchResultSerializer`, `DuplicateDocumentSummarySerializer`, `_DocumentVersionInfo`, `DocumentVersionInfoSerializer`, `DocumentVersionSerializer`, `DocumentVersionLabelSerializer`, `_get_viewable_duplicates` |
|
||||
| `upload.py` | `PostDocumentSerializer` |
|
||||
| `saved_views.py` | `SavedViewFilterRuleSerializer`, `SavedViewSerializer` |
|
||||
| `bulk_edit.py` | `RotateDocumentsSerializer`, `MergeDocumentsSerializer`, `EditPdfDocumentsSerializer`, `RemovePasswordDocumentsSerializer`, `DeleteDocumentsSerializer`, `ReprocessDocumentsSerializer`, `BulkEditSerializer`, `BulkDownloadSerializer`, `BulkEditObjectsSerializer` |
|
||||
| `sharing.py` | `EmailSerializer`, `ShareLinkSerializer`, `ShareLinkBundleSerializer` |
|
||||
| `tasks.py` | `TaskSerializerV10`, `TaskSerializerV9`, `TaskSummarySerializer`, `RunTaskSerializer`, `AcknowledgeTasksViewSerializer` |
|
||||
| `workflows.py` | `WorkflowTriggerSerializer`, `WorkflowActionEmailSerializer`, `WorkflowActionWebhookSerializer`, `WorkflowActionSerializer`, `WorkflowSerializer` |
|
||||
| `system.py` | `UiSettingsViewSerializer`, `TrashSerializer` |
|
||||
|
||||
Note: `ChatStreamingSerializer` is defined in `views.py` today (not
|
||||
`serialisers.py`), directly above `ChatStreamingView`. It moves with
|
||||
`ChatStreamingView` into `documents/views/chat.py` rather than into the
|
||||
serialisers package, preserving its current co-location.
|
||||
|
||||
## External call sites to update
|
||||
|
||||
Only three files import from these two modules today, and all move to
|
||||
importing from the specific new submodule:
|
||||
|
||||
- `src/paperless/urls.py` — ~34 `from documents.views import X` lines, one
|
||||
per viewset/view used in URL routing. Each becomes
|
||||
`from documents.views.<domain> import X`.
|
||||
- `src/paperless_mail/views.py` — `from documents.views import PassUserMixin`
|
||||
becomes `from documents.views.base import PassUserMixin`.
|
||||
- `src/paperless_mail/serialisers.py` — `CorrespondentField`,
|
||||
`DocumentTypeField`, `OwnedObjectSerializer`, `TagsField` move to
|
||||
`from documents.serialisers.metadata import CorrespondentField, DocumentTypeField, TagsField`
|
||||
and `from documents.serialisers.base import OwnedObjectSerializer`.
|
||||
|
||||
## Migration order
|
||||
|
||||
1. Split `serialisers.py` into `documents/serialisers/` first — serializers
|
||||
have no dependency on views, so this half can be verified in isolation.
|
||||
Run the full backend test suite after this step.
|
||||
2. Split `views.py` into `documents/views/`, importing from the new
|
||||
`documents/serialisers/*` modules per the table above. Run the full
|
||||
backend test suite.
|
||||
3. Update the three external call sites (`paperless/urls.py`,
|
||||
`paperless_mail/views.py`, `paperless_mail/serialisers.py`).
|
||||
4. Run `ruff check` / `ruff format` and the full backend test suite once
|
||||
more end to end.
|
||||
|
||||
Splitting serialisers before views (rather than in parallel) means step 2
|
||||
can immediately import finished, correctly-located serializer modules
|
||||
instead of guessing at not-yet-final paths.
|
||||
|
||||
## Risks / error handling
|
||||
|
||||
- **Circular imports**: prevented by construction (serialisers never import
|
||||
from views — see Import direction above). If a genuine cross-domain need
|
||||
is discovered during implementation that seems to require a
|
||||
views→views import cycle (e.g. `UnifiedSearchViewSet` extending
|
||||
`DocumentViewSet` from a different module — both already live in
|
||||
`documents.py` so this doesn't arise), resolve it by moving the shared
|
||||
piece to `base.py` rather than introducing a cycle.
|
||||
- **Missed re-export consumers**: verified via a full-repo grep for
|
||||
`from documents.views import` / `from documents.serialisers import` /
|
||||
`documents.views.` / `documents.serialisers.` before considering the split
|
||||
complete, in case something beyond the three known call sites appears
|
||||
(e.g. in a management command or a rarely-run script).
|
||||
- **Silent behavior drift during move**: since this is a pure reorganization,
|
||||
the full test suite passing after each step (rather than only at the end)
|
||||
is the primary safety net; no new tests are required for this refactor
|
||||
itself.
|
||||
|
||||
## Testing
|
||||
|
||||
No new tests. Existing coverage (`test_views.py`, `test_api_documents.py`,
|
||||
and the rest of the `documents` test suite) is run after each migration step
|
||||
per the ordering above, and must pass unchanged — a failure indicates the
|
||||
move altered behavior, not that new coverage is needed.
|
||||
+71
-22
@@ -5973,7 +5973,7 @@
|
||||
<source>Open <x id="PH" equiv-text="this.title"/> filter</source>
|
||||
<context-group purpose="location">
|
||||
<context context-type="sourcefile">src/app/components/common/filterable-dropdown/filterable-dropdown.component.ts</context>
|
||||
<context context-type="linenumber">828</context>
|
||||
<context context-type="linenumber">831</context>
|
||||
</context-group>
|
||||
</trans-unit>
|
||||
<trans-unit id="7005745151564974365" datatype="html">
|
||||
@@ -6382,27 +6382,6 @@
|
||||
<context context-type="linenumber">94</context>
|
||||
</context-group>
|
||||
</trans-unit>
|
||||
<trans-unit id="5947558132119506443" datatype="html">
|
||||
<source>My documents</source>
|
||||
<context-group purpose="location">
|
||||
<context context-type="sourcefile">src/app/components/common/permissions-filter-dropdown/permissions-filter-dropdown.component.html</context>
|
||||
<context context-type="linenumber">25,26</context>
|
||||
</context-group>
|
||||
</trans-unit>
|
||||
<trans-unit id="231920238966427751" datatype="html">
|
||||
<source>Shared with me</source>
|
||||
<context-group purpose="location">
|
||||
<context context-type="sourcefile">src/app/components/common/permissions-filter-dropdown/permissions-filter-dropdown.component.html</context>
|
||||
<context context-type="linenumber">35,36</context>
|
||||
</context-group>
|
||||
</trans-unit>
|
||||
<trans-unit id="175385209536581523" datatype="html">
|
||||
<source>Shared by me</source>
|
||||
<context-group purpose="location">
|
||||
<context context-type="sourcefile">src/app/components/common/permissions-filter-dropdown/permissions-filter-dropdown.component.html</context>
|
||||
<context context-type="linenumber">45,46</context>
|
||||
</context-group>
|
||||
</trans-unit>
|
||||
<trans-unit id="5151074932731293042" datatype="html">
|
||||
<source>Unowned</source>
|
||||
<context-group purpose="location">
|
||||
@@ -6417,6 +6396,76 @@
|
||||
<context context-type="linenumber">85</context>
|
||||
</context-group>
|
||||
</trans-unit>
|
||||
<trans-unit id="5947558132119506443" datatype="html">
|
||||
<source>My documents</source>
|
||||
<context-group purpose="location">
|
||||
<context context-type="sourcefile">src/app/components/common/permissions-filter-dropdown/permissions-filter-dropdown.component.ts</context>
|
||||
<context context-type="linenumber">101</context>
|
||||
</context-group>
|
||||
</trans-unit>
|
||||
<trans-unit id="1930869169119109336" datatype="html">
|
||||
<source>Owned by <x id="PH" equiv-text="username"/></source>
|
||||
<context-group purpose="location">
|
||||
<context context-type="sourcefile">src/app/components/common/permissions-filter-dropdown/permissions-filter-dropdown.component.ts</context>
|
||||
<context context-type="linenumber">106</context>
|
||||
</context-group>
|
||||
</trans-unit>
|
||||
<trans-unit id="5339682692608120628" datatype="html">
|
||||
<source>Owned by another user</source>
|
||||
<context-group purpose="location">
|
||||
<context context-type="sourcefile">src/app/components/common/permissions-filter-dropdown/permissions-filter-dropdown.component.ts</context>
|
||||
<context context-type="linenumber">107</context>
|
||||
</context-group>
|
||||
</trans-unit>
|
||||
<trans-unit id="231920238966427751" datatype="html">
|
||||
<source>Shared with me</source>
|
||||
<context-group purpose="location">
|
||||
<context context-type="sourcefile">src/app/components/common/permissions-filter-dropdown/permissions-filter-dropdown.component.ts</context>
|
||||
<context context-type="linenumber">117</context>
|
||||
</context-group>
|
||||
</trans-unit>
|
||||
<trans-unit id="1894556100995563325" datatype="html">
|
||||
<source>Not owned by <x id="PH" equiv-text="usernames.join(', ')"/></source>
|
||||
<context-group purpose="location">
|
||||
<context context-type="sourcefile">src/app/components/common/permissions-filter-dropdown/permissions-filter-dropdown.component.ts</context>
|
||||
<context context-type="linenumber">124</context>
|
||||
</context-group>
|
||||
</trans-unit>
|
||||
<trans-unit id="4647949080250052038" datatype="html">
|
||||
<source>Not owned by another user</source>
|
||||
<context-group purpose="location">
|
||||
<context context-type="sourcefile">src/app/components/common/permissions-filter-dropdown/permissions-filter-dropdown.component.ts</context>
|
||||
<context context-type="linenumber">127</context>
|
||||
</context-group>
|
||||
</trans-unit>
|
||||
<trans-unit id="8858352775080403297" datatype="html">
|
||||
<source>Not owned by selected users</source>
|
||||
<context-group purpose="location">
|
||||
<context context-type="sourcefile">src/app/components/common/permissions-filter-dropdown/permissions-filter-dropdown.component.ts</context>
|
||||
<context context-type="linenumber">128</context>
|
||||
</context-group>
|
||||
</trans-unit>
|
||||
<trans-unit id="175385209536581523" datatype="html">
|
||||
<source>Shared by me</source>
|
||||
<context-group purpose="location">
|
||||
<context context-type="sourcefile">src/app/components/common/permissions-filter-dropdown/permissions-filter-dropdown.component.ts</context>
|
||||
<context context-type="linenumber">136</context>
|
||||
</context-group>
|
||||
</trans-unit>
|
||||
<trans-unit id="5140574576358170412" datatype="html">
|
||||
<source>Shared by <x id="PH" equiv-text="username"/></source>
|
||||
<context-group purpose="location">
|
||||
<context context-type="sourcefile">src/app/components/common/permissions-filter-dropdown/permissions-filter-dropdown.component.ts</context>
|
||||
<context context-type="linenumber">141</context>
|
||||
</context-group>
|
||||
</trans-unit>
|
||||
<trans-unit id="391557549689505150" datatype="html">
|
||||
<source>Shared by another user</source>
|
||||
<context-group purpose="location">
|
||||
<context context-type="sourcefile">src/app/components/common/permissions-filter-dropdown/permissions-filter-dropdown.component.ts</context>
|
||||
<context context-type="linenumber">142</context>
|
||||
</context-group>
|
||||
</trans-unit>
|
||||
<trans-unit id="941924371433275463" datatype="html">
|
||||
<source>Global permissions define what areas of the app and API endpoints users can access.</source>
|
||||
<context-group purpose="location">
|
||||
|
||||
+2
-2
@@ -49,7 +49,7 @@
|
||||
</cdk-virtual-scroll-viewport>
|
||||
}
|
||||
@if (editing) {
|
||||
@if (filteredItems.length === 0 && createRef !== undefined) {
|
||||
@if (filteredItems.length === 0 && createRef !== undefined && filterText?.length > 0) {
|
||||
<button class="list-group-item list-group-item-action bg-light" (click)="createClicked()" [disabled]="disabled">
|
||||
<small class="ms-2"><ng-container i18n>Create</ng-container> "{{filterText}}"</small>
|
||||
<i-bs width="1.5em" height="1em" name="plus"></i-bs>
|
||||
@@ -62,7 +62,7 @@
|
||||
</button>
|
||||
}
|
||||
}
|
||||
@if (extraButtonTitle) {
|
||||
@if (extraButtonTitle && (showExtraButtonIfEmpty || filteredItems?.length > 0)) {
|
||||
<button class="list-group-item list-group-item-action bg-light d-flex align-items-center" (click)="extraButtonClicked($event)" [disabled]="disabled">
|
||||
<small class="ms-2 fw-bold">{{extraButtonTitle}}</small>
|
||||
<i-bs width="1.5em" height="1em" name="arrow-right"></i-bs>
|
||||
|
||||
+33
@@ -911,6 +911,25 @@ describe('FilterableDropdownComponent & FilterableDropdownSelectionModel', () =>
|
||||
expect(createSpy).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should only show create when a non-empty filter has no matches', () => {
|
||||
component.selectionModel.items = []
|
||||
component.icon = 'tag-fill'
|
||||
component.editing = true
|
||||
component.createRef = jest.fn()
|
||||
|
||||
fixture.detectChanges()
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Create')
|
||||
component.listFilterEnter()
|
||||
expect(component.createRef).not.toHaveBeenCalled()
|
||||
|
||||
const filterInput: HTMLInputElement =
|
||||
fixture.nativeElement.querySelector('input[type="text"]')
|
||||
filterInput.value = 'FooBar'
|
||||
filterInput.dispatchEvent(new Event('input'))
|
||||
fixture.detectChanges()
|
||||
expect(fixture.nativeElement.textContent).toContain('Create "FooBar"')
|
||||
})
|
||||
|
||||
it('should exclude item and trigger change event', () => {
|
||||
const id = 1
|
||||
const state = ToggleableItemState.Selected
|
||||
@@ -970,4 +989,18 @@ describe('FilterableDropdownComponent & FilterableDropdownSelectionModel', () =>
|
||||
expect(extraButtonClicked).toBeTruthy()
|
||||
expect(applied).toBeFalsy()
|
||||
})
|
||||
|
||||
it('should only show the extra button for an empty result when enabled', () => {
|
||||
component.selectionModel.items = items
|
||||
component.icon = 'tag-fill'
|
||||
component.extraButtonTitle = 'Extra'
|
||||
component.filterText = 'FooBar'
|
||||
|
||||
fixture.detectChanges()
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Extra')
|
||||
|
||||
fixture.componentRef.setInput('showExtraButtonIfEmpty', true)
|
||||
fixture.detectChanges()
|
||||
expect(fixture.nativeElement.textContent).toContain('Extra')
|
||||
})
|
||||
})
|
||||
|
||||
+8
-1
@@ -774,6 +774,9 @@ export class FilterableDropdownComponent
|
||||
@Input()
|
||||
extraButtonTitle: string
|
||||
|
||||
@Input()
|
||||
showExtraButtonIfEmpty: boolean = false
|
||||
|
||||
creating: boolean = false
|
||||
|
||||
@Output()
|
||||
@@ -892,7 +895,11 @@ export class FilterableDropdownComponent
|
||||
this.dropdown.close()
|
||||
}
|
||||
}, 200)
|
||||
} else if (filtered.length == 0 && this.createRef) {
|
||||
} else if (
|
||||
filtered.length == 0 &&
|
||||
this.createRef &&
|
||||
this.filterText?.length > 0
|
||||
) {
|
||||
this.createClicked()
|
||||
}
|
||||
}
|
||||
|
||||
+3
-3
@@ -22,7 +22,7 @@
|
||||
}
|
||||
</div>
|
||||
<div class="me-1">
|
||||
<small i18n>My documents</small>
|
||||
<small>{{ownerFilterLabel}}</small>
|
||||
</div>
|
||||
</button>
|
||||
<button class="list-group-item list-group-item-action d-flex align-items-center p-2 border-top-0 border-start-0 border-end-0 border-bottom" role="menuitem" (click)="setFilter(OwnerFilterType.NOT_SELF)" [disabled]="disabled">
|
||||
@@ -32,7 +32,7 @@
|
||||
}
|
||||
</div>
|
||||
<div class="me-1">
|
||||
<small i18n>Shared with me</small>
|
||||
<small>{{ownerExclusionFilterLabel}}</small>
|
||||
</div>
|
||||
</button>
|
||||
<button class="list-group-item list-group-item-action d-flex align-items-center p-2 border-top-0 border-start-0 border-end-0 border-bottom" role="menuitem" (click)="setFilter(OwnerFilterType.SHARED_BY_ME)" [disabled]="disabled">
|
||||
@@ -42,7 +42,7 @@
|
||||
}
|
||||
</div>
|
||||
<div class="me-1">
|
||||
<small i18n>Shared by me</small>
|
||||
<small>{{sharedByFilterLabel}}</small>
|
||||
</div>
|
||||
</button>
|
||||
<button class="list-group-item list-group-item-action d-flex align-items-center p-2 border-top-0 border-start-0 border-end-0 border-bottom" role="menuitem" (click)="setFilter(OwnerFilterType.UNOWNED)" [disabled]="disabled">
|
||||
|
||||
+52
@@ -94,6 +94,58 @@ describe('PermissionsFilterDropdownComponent', () => {
|
||||
expect(component.isActive).toBeTruthy()
|
||||
})
|
||||
|
||||
it('should describe concrete user filters honestly', () => {
|
||||
component.selectionModel.ownerFilter = OwnerFilterType.SELF
|
||||
component.selectionModel.userID = 1
|
||||
expect(component.ownerFilterLabel).toEqual('Owned by user1')
|
||||
|
||||
component.selectionModel.ownerFilter = OwnerFilterType.NOT_SELF
|
||||
component.selectionModel.excludeUsers = [1]
|
||||
expect(component.ownerExclusionFilterLabel).toEqual('Not owned by user1')
|
||||
|
||||
component.selectionModel.ownerFilter = OwnerFilterType.SHARED_BY_ME
|
||||
component.selectionModel.userID = 1
|
||||
expect(component.sharedByFilterLabel).toEqual('Shared by user1')
|
||||
})
|
||||
|
||||
it('should describe concrete filters when usernames are unavailable', () => {
|
||||
component.selectionModel.ownerFilter = OwnerFilterType.SELF
|
||||
component.selectionModel.userID = 99
|
||||
expect(component.ownerFilterLabel).toEqual('Owned by another user')
|
||||
|
||||
component.selectionModel.ownerFilter = OwnerFilterType.NOT_SELF
|
||||
component.selectionModel.excludeUsers = [99]
|
||||
expect(component.ownerExclusionFilterLabel).toEqual(
|
||||
'Not owned by another user'
|
||||
)
|
||||
|
||||
component.selectionModel.excludeUsers = [98, 99]
|
||||
expect(component.ownerExclusionFilterLabel).toEqual(
|
||||
'Not owned by selected users'
|
||||
)
|
||||
|
||||
component.selectionModel.ownerFilter = OwnerFilterType.SHARED_BY_ME
|
||||
component.selectionModel.userID = 99
|
||||
expect(component.sharedByFilterLabel).toEqual('Shared by another user')
|
||||
})
|
||||
|
||||
it('should retain relative labels for filters bound to the current user', () => {
|
||||
component.selectionModel.userID = currentUserID
|
||||
expect(component.ownerFilterLabel).toEqual('My documents')
|
||||
expect(component.sharedByFilterLabel).toEqual('Shared by me')
|
||||
|
||||
component.selectionModel.excludeUsers = [currentUserID]
|
||||
expect(component.ownerExclusionFilterLabel).toEqual('Shared with me')
|
||||
})
|
||||
|
||||
it('should retain relative labels for inactive filter choices', () => {
|
||||
component.selectionModel.ownerFilter = OwnerFilterType.NONE
|
||||
|
||||
expect(component.ownerFilterLabel).toEqual('My documents')
|
||||
expect(component.ownerExclusionFilterLabel).toEqual('Shared with me')
|
||||
expect(component.sharedByFilterLabel).toEqual('Shared by me')
|
||||
})
|
||||
|
||||
it('should support reset', () => {
|
||||
component.setFilter(OwnerFilterType.OTHERS)
|
||||
expect(component.selectionModel.ownerFilter).not.toEqual(
|
||||
|
||||
+53
@@ -93,6 +93,55 @@ export class PermissionsFilterDropdownComponent extends ComponentWithPermissions
|
||||
)
|
||||
}
|
||||
|
||||
get ownerFilterLabel(): string {
|
||||
if (
|
||||
this.selectionModel?.ownerFilter !== OwnerFilterType.SELF ||
|
||||
this.selectionModel?.userID === this.settingsService.currentUser()?.id
|
||||
) {
|
||||
return $localize`My documents`
|
||||
}
|
||||
|
||||
const username = this.getUsername(this.selectionModel?.userID)
|
||||
return username
|
||||
? $localize`Owned by ${username}`
|
||||
: $localize`Owned by another user`
|
||||
}
|
||||
|
||||
get ownerExclusionFilterLabel(): string {
|
||||
const excludedUsers = this.selectionModel?.excludeUsers ?? []
|
||||
if (
|
||||
this.selectionModel?.ownerFilter !== OwnerFilterType.NOT_SELF ||
|
||||
(excludedUsers.length === 1 &&
|
||||
excludedUsers[0] === this.settingsService.currentUser()?.id)
|
||||
) {
|
||||
return $localize`Shared with me`
|
||||
}
|
||||
|
||||
const usernames = excludedUsers
|
||||
.map((id) => this.getUsername(id))
|
||||
.filter(Boolean)
|
||||
if (usernames.length === excludedUsers.length && usernames.length > 0) {
|
||||
return $localize`Not owned by ${usernames.join(', ')}`
|
||||
}
|
||||
return excludedUsers.length === 1
|
||||
? $localize`Not owned by another user`
|
||||
: $localize`Not owned by selected users`
|
||||
}
|
||||
|
||||
get sharedByFilterLabel(): string {
|
||||
if (
|
||||
this.selectionModel?.ownerFilter !== OwnerFilterType.SHARED_BY_ME ||
|
||||
this.selectionModel?.userID === this.settingsService.currentUser()?.id
|
||||
) {
|
||||
return $localize`Shared by me`
|
||||
}
|
||||
|
||||
const username = this.getUsername(this.selectionModel?.userID)
|
||||
return username
|
||||
? $localize`Shared by ${username}`
|
||||
: $localize`Shared by another user`
|
||||
}
|
||||
|
||||
constructor() {
|
||||
const userService = inject(UserService)
|
||||
|
||||
@@ -164,4 +213,8 @@ export class PermissionsFilterDropdownComponent extends ComponentWithPermissions
|
||||
}
|
||||
this.onChange()
|
||||
}
|
||||
|
||||
private getUsername(userID: number): string {
|
||||
return this.users().find((user) => user.id === userID)?.username
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,6 +64,13 @@ $paperless-card-breakpoints: (
|
||||
}
|
||||
}
|
||||
|
||||
// Popper may place a dropdown above its toggle when the virtual keyboard
|
||||
// reduces the available viewport. Raise the toolbar while a menu is open so
|
||||
// the menu isn't obscured by the fixed navbar.
|
||||
:host ::ng-deep .sticky-top:has(.dropdown-menu.show) {
|
||||
z-index: 1040;
|
||||
}
|
||||
|
||||
@media (max-width: 579.98px) {
|
||||
:host-context(main.mobile-search-hidden) .sticky-top {
|
||||
top: calc(3.5rem - 2px); // height of navbar only when search is hidden
|
||||
|
||||
@@ -9,5 +9,6 @@ export function pngxPopperOptions(config: Partial<Options>): Partial<Options> {
|
||||
padding: 10,
|
||||
}
|
||||
}
|
||||
|
||||
return config
|
||||
}
|
||||
|
||||
@@ -223,7 +223,27 @@ class WriteBatch:
|
||||
)
|
||||
time.sleep(sleep_s)
|
||||
|
||||
self._raw_writer = self._backend._index.writer()
|
||||
# Open a fresh Index (and thus a fresh Tantivy ManagedDirectory)
|
||||
# for the write, rather than reusing the process-local cached
|
||||
# index. ManagedDirectory loads its GC bookkeeping (.managed.json)
|
||||
# once, at construction, and never re-reads it; paperless runs
|
||||
# several long-lived processes (Granian workers, Celery workers)
|
||||
# that take turns writing under the file lock above. A cached,
|
||||
# long-lived writer index would carry a stale managed-files view
|
||||
# and, on commit, overwrite .managed.json with that stale view -
|
||||
# permanently losing track of segment files other processes
|
||||
# registered in the meantime, so they can never be garbage
|
||||
# collected. Reopening fresh here always picks up the current
|
||||
# on-disk state. The long-lived self._backend._index is used for
|
||||
# reads only and is reloaded (not reopened) after commit below.
|
||||
write_index = tantivy.Index(
|
||||
build_schema(),
|
||||
path=str(self._backend._path),
|
||||
)
|
||||
register_tokenizers(write_index, settings.SEARCH_LANGUAGE)
|
||||
self._raw_writer = write_index.writer()
|
||||
else:
|
||||
self._raw_writer = self._backend._index.writer()
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from django.contrib.auth.models import Group
|
||||
from django.contrib.auth.models import User
|
||||
@@ -21,6 +24,17 @@ from documents.tests.factories import UserFactory
|
||||
|
||||
pytestmark = [pytest.mark.search, pytest.mark.django_db]
|
||||
|
||||
# Extensions of actual Tantivy segment data files, as opposed to its own
|
||||
# bookkeeping files (meta.json, .managed.json, lock files).
|
||||
_SEGMENT_FILE_EXTENSIONS = (
|
||||
".fast",
|
||||
".fieldnorm",
|
||||
".idx",
|
||||
".pos",
|
||||
".store",
|
||||
".term",
|
||||
)
|
||||
|
||||
|
||||
class TestWriteBatch:
|
||||
"""Test WriteBatch context manager functionality."""
|
||||
@@ -1014,3 +1028,63 @@ class TestHighlightHits:
|
||||
hits = backend.highlight_hits("quick", [doc.pk])
|
||||
|
||||
assert len(hits) == 0
|
||||
|
||||
|
||||
class TestIndexDirectoryGarbageCollection:
|
||||
"""Regression tests for Tantivy segment files leaking on disk when
|
||||
multiple long-lived worker processes (Granian/Celery) take turns writing
|
||||
to the same on-disk index (issue #13679)."""
|
||||
|
||||
def test_no_permanently_orphaned_segment_files_across_worker_processes(
|
||||
self,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""Simulate two long-lived worker processes, each with its own
|
||||
process-local ``TantivyBackend``/``Index`` opened once at process
|
||||
start, alternating turns as the writer -- exactly how paperless runs
|
||||
in production (several Granian + Celery worker processes).
|
||||
|
||||
Every segment file physically present on disk must still be tracked
|
||||
in Tantivy's ``.managed.json`` bookkeeping; otherwise it can never be
|
||||
garbage collected by anyone again and the index directory grows
|
||||
without bound.
|
||||
"""
|
||||
index_dir = tmp_path / "index"
|
||||
index_dir.mkdir()
|
||||
|
||||
worker_a = TantivyBackend(path=index_dir)
|
||||
worker_a.open()
|
||||
worker_b = TantivyBackend(path=index_dir)
|
||||
worker_b.open()
|
||||
workers = [worker_a, worker_b]
|
||||
|
||||
docs = [
|
||||
DocumentFactory.create(checksum=f"GC{i}", title=f"gc doc {i}")
|
||||
for i in range(5)
|
||||
]
|
||||
|
||||
try:
|
||||
# Alternate writers across many commits, repeatedly upserting the
|
||||
# same documents so segments accumulate and get superseded,
|
||||
# forcing the delete+add upsert pattern and eventual merges.
|
||||
for i in range(30):
|
||||
worker = workers[i % len(workers)]
|
||||
doc = docs[i % len(docs)]
|
||||
worker.add_or_update(doc)
|
||||
finally:
|
||||
worker_a.close()
|
||||
worker_b.close()
|
||||
|
||||
managed_path = index_dir / ".managed.json"
|
||||
managed = set(json.loads(managed_path.read_text()))
|
||||
on_disk = {
|
||||
p.name
|
||||
for p in index_dir.iterdir()
|
||||
if p.is_file() and p.suffix in _SEGMENT_FILE_EXTENSIONS
|
||||
}
|
||||
orphans = on_disk - managed
|
||||
|
||||
assert not orphans, (
|
||||
"Segment files present on disk but absent from Tantivy's "
|
||||
f".managed.json bookkeeping (permanently un-collectible): {orphans}"
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user