A community-supported supercharged document management system: scan, index and archive all your documents
Python aiangulararchivingdjangodmsdocument-managementdocument-management-systemllmmachine-learningocroptical-character-recognitionpdf
Merge branch 'dev' into feature-bulk-edit
jonaswinkler8b57967836d7
diff --cc src-ui/src/app/app.module.tsindex 887dc7ffd,f935b7701..914854892--- a/src-ui/src/app/app.module.ts+++ b/src-ui/src/app/app.module.ts@@@ -48,9 -51,9 +51,10 @@@ import { PdfViewerModule } from 'ng2-pdimport { WelcomeWidgetComponent } from './components/dashboard/widgets/welcome-widget/welcome-widget.component';import { YesNoPipe } from './pipes/yes-no.pipe';import { FileSizePipe } from './pipes/file-size.pipe';+ import { FilterPipe } from './pipes/filter.pipe';import { DocumentTitlePipe } from './pipes/document-title.pipe';import { MetadataCollapseComponent } from './components/document-detail/metadata-collapse/metadata-collapse.component';+import { SelectDialogComponent } from './components/common/select-dialog/select-dialog.component';@NgModule({declarations: [@@@ -91,9 -97,9 +98,10 @@@WelcomeWidgetComponent,YesNoPipe,FileSizePipe,+ FilterPipe,DocumentTitlePipe,- MetadataCollapseComponent+ MetadataCollapseComponent,+ SelectDialogComponent],imports: [BrowserModule,diff --cc src-ui/src/app/components/document-list/document-list.component.htmlindex 396e7e12d,acbfd3602..be2ed4847--- a/src-ui/src/app/components/document-list/document-list.component.html+++ b/src-ui/src/app/components/document-list/document-list.component.html@@@ -155,5 -117,5 +148,5 @@@<div class=" m-n2 row" *ngIf="displayMode == 'smallCards'">- <app-document-card-small [selected]="list.isSelected(d)" (selectedChange)="list.setSelected(d, $event)" [document]="d" *ngFor="let d of list.documents" (clickTag)="filterByTag($event)" (clickCorrespondent)="filterByCorrespondent($event)"></app-document-card-small>- <app-document-card-small [document]="d" *ngFor="let d of list.documents" (clickTag)="clickTag($event)" (clickCorrespondent)="clickCorrespondent($event)"></app-document-card-small>++ <app-document-card-small [selected]="list.isSelected(d)" (selectedChange)="list.setSelected(d, $event)" [document]="d" *ngFor="let d of list.documents" (clickTag)="clickTag($event)" (clickCorrespondent)="clickCorrespondent($event)"></app-document-card-small></div>diff --cc src-ui/src/app/components/document-list/document-list.component.tsindex ce4ebec73,4b711f9dc..1bd1e5c7f--- a/src-ui/src/app/components/document-list/document-list.component.ts+++ b/src-ui/src/app/components/document-list/document-list.component.ts@@@ -1,22 -1,12 +1,19 @@@- import { Component, OnInit } from '@angular/core';- import { Title } from '@angular/platform-browser';- import { ActivatedRoute } from '@angular/router';+ import { Component, OnInit, ViewChild } from '@angular/core';+ import { ActivatedRoute, Router } from '@angular/router';import { NgbModal } from '@ng-bootstrap/ng-bootstrap';+import { Observable } from 'rxjs';+import { map } from 'rxjs/operators';- import { cloneFilterRules, FilterRule } from 'src/app/data/filter-rule';- import { FILTER_CORRESPONDENT, FILTER_DOCUMENT_TYPE, FILTER_HAS_TAG, FILTER_RULE_TYPES } from 'src/app/data/filter-rule-type';- import { SavedViewConfig } from 'src/app/data/saved-view-config';+ import { PaperlessSavedView } from 'src/app/data/paperless-saved-view';import { DocumentListViewService } from 'src/app/services/document-list-view.service';-import { DOCUMENT_SORT_FIELDS } from 'src/app/services/rest/document.service';+import { CorrespondentService } from 'src/app/services/rest/correspondent.service';+import { DocumentTypeService } from 'src/app/services/rest/document-type.service';+import { DocumentService, DOCUMENT_SORT_FIELDS } from 'src/app/services/rest/document.service';+import { TagService } from 'src/app/services/rest/tag.service';- import { SavedViewConfigService } from 'src/app/services/saved-view-config.service';+ import { SavedViewService } from 'src/app/services/rest/saved-view.service';import { Toast, ToastService } from 'src/app/services/toast.service';- import { environment } from 'src/environments/environment';+ import { FilterEditorComponent } from '../filter-editor/filter-editor.component';+import { ConfirmDialogComponent } from '../common/confirm-dialog/confirm-dialog.component';+import { SelectDialogComponent } from '../common/select-dialog/select-dialog.component';import { SaveViewConfigDialogComponent } from './save-view-config-dialog/save-view-config-dialog.component';@Component({@@@ -28,20 -18,16 +25,20 @@@ export class DocumentListComponent implconstructor(public list: DocumentListViewService,- public savedViewConfigService: SavedViewConfigService,+ public savedViewService: SavedViewService,public route: ActivatedRoute,+ private router: Router,private toastService: ToastService,- public modalService: NgbModal) { }+ public modalService: NgbModal,- private titleService: Title,+ private correspondentService: CorrespondentService,+ private documentTypeService: DocumentTypeService,+ private tagService: TagService,+ private documentService: DocumentService) { }- displayMode = 'smallCards' // largeCards, smallCards, details+ @ViewChild("filterEditor")+ private filterEditor: FilterEditorComponent- filterRules: FilterRule[] = []- showFilter = false+ displayMode = 'smallCards' // largeCards, smallCards, detailsget isFiltered() {return this.list.filterRules?.length > 0@@@ -113,158 -99,16 +110,130 @@@})}- filterByTag(tag_id: number) {- let filterRules = this.list.filterRules- if (filterRules.find(rule => rule.type.id == FILTER_HAS_TAG && rule.value == tag_id)) {- return- }-- filterRules.push({type: FILTER_RULE_TYPES.find(t => t.id == FILTER_HAS_TAG), value: tag_id})- this.filterRules = filterRules- this.applyFilterRules()+ clickTag(tagID: number) {+ this.filterEditor.toggleTag(tagID)}- filterByCorrespondent(correspondent_id: number) {- let filterRules = this.list.filterRules- let existing_rule = filterRules.find(rule => rule.type.id == FILTER_CORRESPONDENT)- if (existing_rule && existing_rule.value == correspondent_id) {- return- } else if (existing_rule) {- existing_rule.value = correspondent_id- } else {- filterRules.push({type: FILTER_RULE_TYPES.find(t => t.id == FILTER_CORRESPONDENT), value: correspondent_id})- }- this.filterRules = filterRules- this.applyFilterRules()+ clickCorrespondent(correspondentID: number) {+ this.filterEditor.toggleCorrespondent(correspondentID)}- filterByDocumentType(document_type_id: number) {- let filterRules = this.list.filterRules- let existing_rule = filterRules.find(rule => rule.type.id == FILTER_DOCUMENT_TYPE)- if (existing_rule && existing_rule.value == document_type_id) {- return- } else if (existing_rule) {- existing_rule.value = document_type_id- } else {- filterRules.push({type: FILTER_RULE_TYPES.find(t => t.id == FILTER_DOCUMENT_TYPE), value: document_type_id})- }- this.filterRules = filterRules- this.applyFilterRules()+ clickDocumentType(documentTypeID: number) {+ this.filterEditor.toggleDocumentType(documentTypeID)}+ private executeBulkOperation(method: string, args): Observable<any> {+ return this.documentService.bulkEdit(Array.from(this.list.selected), method, args).pipe(+ map(r => {++ this.list.reload()+ this.list.selectNone()++ return r+ })+ )+ }++ bulkSetCorrespondent() {+ let modal = this.modalService.open(SelectDialogComponent, {backdrop: 'static'})+ modal.componentInstance.title = "Select correspondent"+ modal.componentInstance.message = `Select the correspondent you wish to assign to ${this.list.selected.size} selected document(s):`+ this.correspondentService.listAll().subscribe(response => {+ modal.componentInstance.objects = response.results+ })+ modal.componentInstance.selectClicked.subscribe(selectedId => {+ this.executeBulkOperation('set_correspondent', {"correspondent": selectedId}).subscribe(+ response => {+ modal.close()+ }+ )+ })+ }++ bulkRemoveCorrespondent() {+ let modal = this.modalService.open(ConfirmDialogComponent, {backdrop: 'static'})+ modal.componentInstance.title = "Remove correspondent"+ modal.componentInstance.message = `This operation will remove the correspondent from all ${this.list.selected.size} selected document(s).`+ modal.componentInstance.confirmClicked.subscribe(() => {+ this.executeBulkOperation('set_correspondent', {"correspondent": null}).subscribe(r => {+ modal.close()+ })+ })+ }++ bulkSetDocumentType() {+ let modal = this.modalService.open(SelectDialogComponent, {backdrop: 'static'})+ modal.componentInstance.title = "Select document type"+ modal.componentInstance.message = `Select the document type you wish to assign to ${this.list.selected.size} selected document(s):`+ this.documentTypeService.listAll().subscribe(response => {+ modal.componentInstance.objects = response.results+ })+ modal.componentInstance.selectClicked.subscribe(selectedId => {+ this.executeBulkOperation('set_document_type', {"document_type": selectedId}).subscribe(+ response => {+ modal.close()+ }+ )+ })+ }++ bulkRemoveDocumentType() {+ let modal = this.modalService.open(ConfirmDialogComponent, {backdrop: 'static'})+ modal.componentInstance.title = "Remove document type"+ modal.componentInstance.message = `This operation will remove the document type from all ${this.list.selected.size} selected document(s).`+ modal.componentInstance.confirmClicked.subscribe(() => {+ this.executeBulkOperation('set_document_type', {"document_type": null}).subscribe(r => {+ modal.close()+ })+ })+ }++ bulkAddTag() {+ let modal = this.modalService.open(SelectDialogComponent, {backdrop: 'static'})+ modal.componentInstance.title = "Select tag"+ modal.componentInstance.message = `Select the tag you wish to assign to ${this.list.selected.size} selected document(s):`+ this.tagService.listAll().subscribe(response => {+ modal.componentInstance.objects = response.results+ })+ modal.componentInstance.selectClicked.subscribe(selectedId => {+ this.executeBulkOperation('add_tag', {"tag": selectedId}).subscribe(+ response => {+ modal.close()+ }+ )+ })+ }++ bulkRemoveTag() {+ let modal = this.modalService.open(SelectDialogComponent, {backdrop: 'static'})+ modal.componentInstance.title = "Select tag"+ modal.componentInstance.message = `Select the tag you wish to remove from ${this.list.selected.size} selected document(s):`+ this.tagService.listAll().subscribe(response => {+ modal.componentInstance.objects = response.results+ })+ modal.componentInstance.selectClicked.subscribe(selectedId => {+ this.executeBulkOperation('remove_tag', {"tag": selectedId}).subscribe(+ response => {+ modal.close()+ }+ )+ })+ }++ bulkDelete() {+ let modal = this.modalService.open(ConfirmDialogComponent, {backdrop: 'static'})+ modal.componentInstance.delayConfirm(5)+ modal.componentInstance.title = "Delete confirm"+ modal.componentInstance.messageBold = `This operation will permanently delete all ${this.list.selected.size} selected document(s).`+ modal.componentInstance.message = `This operation cannot be undone.`+ modal.componentInstance.btnClass = "btn-danger"+ modal.componentInstance.btnCaption = "Delete document(s)"+ modal.componentInstance.confirmClicked.subscribe(() => {+ this.executeBulkOperation("delete", {}).subscribe(+ response => {+ modal.close()+ }+ )- })++ })+ }}diff --cc src-ui/src/app/services/document-list-view.service.tsindex b3fe351ac,7405fcd24..05c46750d--- a/src-ui/src/app/services/document-list-view.service.ts+++ b/src-ui/src/app/services/document-list-view.service.ts@@@ -90,12 -90,12 +90,12 @@@ export class DocumentListViewServicereload(onFinish?) {this.isReloading = true- this.documentService.list(+ this.documentService.listFiltered(this.currentPage,this.currentPageSize,- this.view.sortField,- this.view.sortDirection,- this.view.filterRules).subscribe(+ this.view.sort_field,+ this.view.sort_reverse,+ this.view.filter_rules).subscribe(result => {this.collectionSize = result.countthis.documents = result.results@@@ -116,9 -116,8 +116,9 @@@set filterRules(filterRules: FilterRule[]) {//we're going to clone the filterRules object, since we don't//want changes in the filter editor to propagate into here right away.- this.view.filterRules = cloneFilterRules(filterRules)+ this.view.filter_rules = cloneFilterRules(filterRules)this.reload()+ this.reduceSelectionToFilter()this.saveDocumentListView()}@@@ -192,51 -191,7 +192,50 @@@}}+ selected = new Set<number>()++ selectNone() {+ this.selected.clear()+ }++ private reduceSelectionToFilter() {+ if (this.selected.size > 0) {+ this.documentService.listAllFilteredIds(this.filterRules).subscribe(ids => {+ let subset = new Set<number>()+ for (let id of ids) {+ if (this.selected.has(id)) {+ subset.add(id)+ }+ }+ this.selected = subset+ })+ }+ }++ selectAll() {+ this.documentService.listAllFilteredIds(this.filterRules).subscribe(ids => ids.forEach(id => this.selected.add(id)))+ }++ selectPage() {+ this.selected.clear()+ this.documents.forEach(doc => {+ this.selected.add(doc.id)+ })+ }++ isSelected(d: PaperlessDocument) {+ return this.selected.has(d.id)+ }++ setSelected(d: PaperlessDocument, value: boolean) {+ if (value) {+ this.selected.add(d.id)+ } else if (!value) {+ this.selected.delete(d.id)+ }+ }+- constructor(private documentService: DocumentService) {+ constructor(private documentService: DocumentService) {let documentListViewConfigJson = sessionStorage.getItem(DOCUMENT_LIST_SERVICE.CURRENT_VIEW_CONFIG)if (documentListViewConfigJson) {try {diff --cc src-ui/src/app/services/rest/abstract-paperless-service.tsindex d05b4aced,93e1a0c85..f57956754--- a/src-ui/src/app/services/rest/abstract-paperless-service.ts+++ b/src-ui/src/app/services/rest/abstract-paperless-service.ts@@@ -54,9 -52,9 +52,9 @@@ export abstract class AbstractPaperlessprivate _listAll: Observable<Results<T>>- listAll(sortField?: string, sortDirection?: string, extraParams?): Observable<Results<T>> {- listAll(ordering?: string, extraParams?): Observable<Results<T>> {++ listAll(sortField?: string, sortReverse?: boolean, extraParams?): Observable<Results<T>> {if (!this._listAll) {- this._listAll = this.list(1, 100000, sortField, sortDirection, extraParams).pipe(- this._listAll = this.list(1, 100000, ordering, extraParams).pipe(++ this._listAll = this.list(1, 100000, sortField, sortReverse, extraParams).pipe(publishReplay(1),refCount())diff --cc src-ui/src/app/services/rest/document.service.tsindex 99ec1f3ee,f50620d23..c132fa856--- a/src-ui/src/app/services/rest/document.service.ts+++ b/src-ui/src/app/services/rest/document.service.ts@@@ -64,8 -61,8 +61,8 @@@ export class DocumentService extends Abreturn doc}- listFiltered(page?: number, pageSize?: number, sortField?: string, sortDirection?: string, filterRules?: FilterRule[], extraParams = {}): Observable<Results<PaperlessDocument>> {- return this.list(page, pageSize, sortField, sortDirection, Object.assign(extraParams, this.filterRulesToQueryParams(filterRules))).pipe(- list(page?: number, pageSize?: number, sortField?: string, sortReverse?: boolean, filterRules?: FilterRule[]): Observable<Results<PaperlessDocument>> {- return super.list(page, pageSize, sortField, sortReverse, this.filterRulesToQueryParams(filterRules)).pipe(++ listFiltered(page?: number, pageSize?: number, sortField?: string, sortReverse?: boolean, filterRules?: FilterRule[], extraParams = {}): Observable<Results<PaperlessDocument>> {++ return this.list(page, pageSize, sortField, sortReverse, Object.assign(extraParams, this.filterRulesToQueryParams(filterRules))).pipe(map(results => {results.results.forEach(doc => this.addObservablesToDocument(doc))return resultsdiff --cc src/documents/serialisers.pyindex 92fc35719,2def07fdd..e34279b1a--- a/src/documents/serialisers.py+++ b/src/documents/serialisers.py@@@ -3,8 -3,8 +3,9 @@@ from django.utils.text import slugiffrom rest_framework import serializersfrom rest_framework.fields import SerializerMethodField+from . import bulk_edit- from .models import Correspondent, Tag, Document, Log, DocumentType+ from .models import Correspondent, Tag, Document, Log, DocumentType, \+ SavedView, SavedViewFilterRulefrom .parsers import is_mime_type_supported@@@ -163,54 -141,43 +164,91 @@@ class LogSerializer(serializers.ModelSe)+ class SavedViewFilterRuleSerializer(serializers.ModelSerializer):++ class Meta:+ model = SavedViewFilterRule+ fields = ["rule_type", "value"]+++ class SavedViewSerializer(serializers.ModelSerializer):++ filter_rules = SavedViewFilterRuleSerializer(many=True)++ class Meta:+ model = SavedView+ depth = 1+ fields = ["id", "name", "show_on_dashboard", "show_in_sidebar",+ "sort_field", "sort_reverse", "filter_rules"]++ def update(self, instance, validated_data):+ if 'filter_rules' in validated_data:+ rules_data = validated_data.pop('filter_rules')+ else:+ rules_data = None+ super(SavedViewSerializer, self).update(instance, validated_data)+ if rules_data:+ SavedViewFilterRule.objects.filter(saved_view=instance).delete()+ for rule_data in rules_data:+ SavedViewFilterRule.objects.create(saved_view=instance, **rule_data)+ return instance++ def create(self, validated_data):+ rules_data = validated_data.pop('filter_rules')+ saved_view = SavedView.objects.create(**validated_data)+ for rule_data in rules_data:+ SavedViewFilterRule.objects.create(saved_view=saved_view, **rule_data)+ return saved_view+++class BulkEditSerializer(serializers.Serializer):++ documents = serializers.ListField(+ child=serializers.IntegerField(),+ label="Documents",+ write_only=True+ )++ method = serializers.ChoiceField(+ choices=[+ "set_correspondent",+ "set_document_type",+ "add_tag",+ "remove_tag",+ "delete"+ ],+ label="Method",+ write_only=True,+ )++ parameters = serializers.DictField(allow_empty=True)++ def validate_documents(self, documents):+ count = Document.objects.filter(id__in=documents).count()+ if not count == len(documents):+ raise serializers.ValidationError(+ "Some documents don't exist or were specified twice.")+ return documents++ def validate_method(self, method):+ if method == "set_correspondent":+ return bulk_edit.set_correspondent+ elif method == "set_document_type":+ return bulk_edit.set_document_type+ elif method == "add_tag":+ return bulk_edit.add_tag+ elif method == "remove_tag":+ return bulk_edit.remove_tag+ elif method == "delete":+ return bulk_edit.delete+ else:+ raise serializers.ValidationError("Unsupported method.")++ def validate(self, attrs):++ return attrs++class PostDocumentSerializer(serializers.Serializer):document = serializers.FileField(diff --cc src/documents/views.pyindex 5e173d703,36d3445c4..3924f3d1a--- a/src/documents/views.py+++ b/src/documents/views.py@@@ -47,7 -47,7 +47,8 @@@ from .serialisers importTagSerializer,DocumentTypeSerializer,PostDocumentSerializer,- SavedViewSerializer++ SavedViewSerializer,+ BulkEditSerializer)@@@ -256,39 -241,22 +257,55 @@@ class LogViewSet(ReadOnlyModelViewSet)ordering_fields = ("created",)+ class SavedViewViewSet(ModelViewSet):+ model = SavedView++ queryset = SavedView.objects.all()+ serializer_class = SavedViewSerializer+ pagination_class = StandardPagination+ permission_classes = (IsAuthenticated,)++ def get_queryset(self):+ user = self.request.user+ return SavedView.objects.filter(user=user)++ def perform_create(self, serializer):+ serializer.save(user=self.request.user)+++class BulkEditView(APIView):++ permission_classes = (IsAuthenticated,)+ serializer_class = BulkEditSerializer+ parser_classes = (parsers.JSONParser,)++ def get_serializer_context(self):+ return {+ 'request': self.request,+ 'format': self.format_kwarg,+ 'view': self+ }++ def get_serializer(self, *args, **kwargs):+ kwargs['context'] = self.get_serializer_context()+ return self.serializer_class(*args, **kwargs)++ def post(self, request, *args, **kwargs):+ serializer = self.get_serializer(data=request.data)+ serializer.is_valid(raise_exception=True)++ method = serializer.validated_data.get("method")+ parameters = serializer.validated_data.get("parameters")+ documents = serializer.validated_data.get("documents")++ try:+ # TODO: parameter validation+ result = method(documents, **parameters)+ return Response({"result": result})+ except Exception as e:+ return HttpResponseBadRequest(str(e))++class PostDocumentView(APIView):permission_classes = (IsAuthenticated,)diff --cc src/paperless/urls.pyindex dc416f05f,079971bb3..831eb02b4--- a/src/paperless/urls.py+++ b/src/paperless/urls.py@@@ -18,7 -18,7 +18,8 @@@ from documents.views importSearchAutoCompleteView,StatisticsView,PostDocumentView,- SavedViewViewSet++ SavedViewViewSet,+ BulkEditView)from paperless.views import FaviconView