-
-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy pathpaperlessService.js
1220 lines (1044 loc) · 37.5 KB
/
paperlessService.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// services/paperlessService.js
const axios = require('axios');
const config = require('../config/config');
const fs = require('fs');
const path = require('path');
const { parse, isValid, parseISO } = require('date-fns');
class PaperlessService {
constructor() {
this.client = null;
this.tagCache = new Map();
this.customFieldCache = new Map();
this.lastTagRefresh = 0;
this.CACHE_LIFETIME = 3000; // 3 Sekunden
}
initialize() {
if (!this.client && config.paperless.apiUrl && config.paperless.apiToken) {
this.client = axios.create({
baseURL: config.paperless.apiUrl,
headers: {
'Authorization': `Token ${config.paperless.apiToken}`,
'Content-Type': 'application/json'
}
});
}
}
async getThumbnailImage(documentId) {
this.initialize();
try {
const response = await this.client.get(`/documents/${documentId}/thumb/`, {
responseType: 'arraybuffer'
});
if (response.data && response.data.byteLength > 0) {
return Buffer.from(response.data);
}
console.warn(`[DEBUG] No thumbnail data for document ${documentId}`);
return null;
} catch (error) {
console.error(`[ERROR] fetching thumbnail for document ${documentId}:`, error.message);
if (error.response) {
console.log('[ERROR] status:', error.response.status);
console.log('[ERROR] headers:', error.response.headers);
}
return null; // Behalten Sie das return null bei, damit der Prozess weiterlaufen kann
}
}
// Aktualisiert den Tag-Cache, wenn er älter als CACHE_LIFETIME ist
async ensureTagCache() {
const now = Date.now();
if (this.tagCache.size === 0 || (now - this.lastTagRefresh) > this.CACHE_LIFETIME) {
await this.refreshTagCache();
}
}
// Lädt alle existierenden Tags
async refreshTagCache() {
try {
console.log('[DEBUG] Refreshing tag cache...');
this.tagCache.clear();
let nextUrl = '/tags/';
while (nextUrl) {
const response = await this.client.get(nextUrl);
response.data.results.forEach(tag => {
this.tagCache.set(tag.name.toLowerCase(), tag);
});
nextUrl = response.data.next;
}
this.lastTagRefresh = Date.now();
console.log(`[DEBUG] Tag cache refreshed. Found ${this.tagCache.size} tags.`);
} catch (error) {
console.error('[ERROR] refreshing tag cache:', error.message);
throw error;
}
}
async initializeWithCredentials(apiUrl, apiToken) {
this.client = axios.create({
baseURL: apiUrl,
headers: {
'Authorization': `Token ${apiToken}`,
'Content-Type': 'application/json'
}
});
// Test the connection
try {
await this.client.get('/');
return true;
} catch (error) {
console.error('[ERROR] Failed to initialize with credentials:', error.message);
this.client = null;
return false;
}
}
async createCustomFieldSafely(fieldName, fieldType, default_currency) {
try {
// Try to create the field first
const response = await this.client.post('/custom_fields/', {
name: fieldName,
data_type: fieldType,
extra_data: {
default_currency: default_currency || null
}
});
const newField = response.data;
console.log(`[DEBUG] Successfully created custom field "${fieldName}" with ID ${newField.id}`);
this.customFieldCache.set(fieldName.toLowerCase(), newField);
return newField;
} catch (error) {
if (error.response?.status === 400) {
await this.refreshCustomFieldCache();
const existingField = await this.findExistingCustomField(fieldName);
if (existingField) {
return existingField;
}
}
throw error; // When couldn't find the field, rethrow the error
}
}
async getExistingCustomFields(documentId) {
try {
const response = await this.client.get(`/documents/${documentId}/`);
console.log('[DEBUG] Document response custom fields:', response.data.custom_fields);
return response.data.custom_fields || [];
} catch (error) {
console.error(`[ERROR] fetching document ${documentId}:`, error.message);
return [];
}
}
async findExistingCustomField(fieldName) {
const normalizedName = fieldName.toLowerCase();
const cachedField = this.customFieldCache.get(normalizedName);
if (cachedField) {
console.log(`[DEBUG] Found custom field "${fieldName}" in cache with ID ${cachedField.id}`);
return cachedField;
}
try {
const response = await this.client.get('/custom_fields/', {
params: {
name__iexact: normalizedName // Case-insensitive exact match
}
});
if (response.data.results.length > 0) {
const foundField = response.data.results[0];
console.log(`[DEBUG] Found existing custom field "${fieldName}" via API with ID ${foundField.id}`);
this.customFieldCache.set(normalizedName, foundField);
return foundField;
}
} catch (error) {
console.warn(`[ERROR] searching for custom field "${fieldName}":`, error.message);
}
return null;
}
async refreshCustomFieldCache() {
try {
console.log('[DEBUG] Refreshing custom field cache...');
this.customFieldCache.clear();
let nextUrl = '/custom_fields/';
while (nextUrl) {
const response = await this.client.get(nextUrl);
response.data.results.forEach(field => {
this.customFieldCache.set(field.name.toLowerCase(), field);
});
nextUrl = response.data.next;
}
this.lastCustomFieldRefresh = Date.now();
console.log(`[DEBUG] Custom field cache refreshed. Found ${this.customFieldCache.size} fields.`);
} catch (error) {
console.error('[ERROR] refreshing custom field cache:', error.message);
throw error;
}
}
async findExistingTag(tagName) {
const normalizedName = tagName.toLowerCase();
// 1. Zuerst im Cache suchen
const cachedTag = this.tagCache.get(normalizedName);
if (cachedTag) {
console.log(`[DEBUG] Found tag "${tagName}" in cache with ID ${cachedTag.id}`);
return cachedTag;
}
// 2. Direkte API-Suche
try {
const response = await this.client.get('/tags/', {
params: {
name__iexact: normalizedName // Case-insensitive exact match
}
});
if (response.data.results.length > 0) {
const foundTag = response.data.results[0];
console.log(`[DEBUG] Found existing tag "${tagName}" via API with ID ${foundTag.id}`);
this.tagCache.set(normalizedName, foundTag);
return foundTag;
}
} catch (error) {
console.warn(`[ERROR] searching for tag "${tagName}":`, error.message);
}
return null;
}
async createTagSafely(tagName) {
const normalizedName = tagName.toLowerCase();
try {
// Versuche zuerst, den Tag zu erstellen
const response = await this.client.post('/tags/', { name: tagName });
const newTag = response.data;
console.log(`[DEBUG] Successfully created tag "${tagName}" with ID ${newTag.id}`);
this.tagCache.set(normalizedName, newTag);
return newTag;
} catch (error) {
if (error.response?.status === 400) {
// Bei einem 400er Fehler könnte der Tag bereits existieren
// Aktualisiere den Cache und suche erneut
await this.refreshTagCache();
// Suche nochmal nach dem Tag
const existingTag = await this.findExistingTag(tagName);
if (existingTag) {
return existingTag;
}
}
throw error; // Wenn wir den Tag nicht finden konnten, werfen wir den Fehler weiter
}
}
async processTags(tagNames) {
try {
this.initialize();
await this.ensureTagCache();
// Input validation
if (!tagNames) {
console.warn('[DEBUG] No tags provided to processTags');
return { tagIds: [], errors: [] };
}
// Convert to array if string is passed
const tagsArray = typeof tagNames === 'string'
? [tagNames]
: Array.isArray(tagNames)
? tagNames
: [];
if (tagsArray.length === 0) {
console.warn('[DEBUG] No valid tags to process');
return { tagIds: [], errors: [] };
}
const tagIds = [];
const errors = [];
const processedTags = new Set(); // Prevent duplicates
// Process regular tags
for (const tagName of tagsArray) {
if (!tagName || typeof tagName !== 'string') {
console.warn(`[DEBUG] Skipping invalid tag name: ${tagName}`);
errors.push({ tagName, error: 'Invalid tag name' });
continue;
}
const normalizedName = tagName.toLowerCase().trim();
// Skip empty or already processed tags
if (!normalizedName || processedTags.has(normalizedName)) {
continue;
}
try {
// Search for existing tag first
let tag = await this.findExistingTag(tagName);
// If no existing tag found, create new one
if (!tag) {
tag = await this.createTagSafely(tagName);
}
if (tag && tag.id) {
tagIds.push(tag.id);
processedTags.add(normalizedName);
}
} catch (error) {
console.error(`[ERROR] processing tag "${tagName}":`, error.message);
errors.push({ tagName, error: error.message });
}
}
// Add AI-Processed tag if enabled
if (process.env.ADD_AI_PROCESSED_TAG === 'yes' && process.env.AI_PROCESSED_TAG_NAME) {
try {
const aiTagName = process.env.AI_PROCESSED_TAG_NAME;
let aiTag = await this.findExistingTag(aiTagName);
if (!aiTag) {
aiTag = await this.createTagSafely(aiTagName);
}
if (aiTag && aiTag.id) {
tagIds.push(aiTag.id);
}
} catch (error) {
console.error(`[ERROR] processing AI tag "${process.env.AI_PROCESSED_TAG_NAME}":`, error.message);
errors.push({ tagName: process.env.AI_PROCESSED_TAG_NAME, error: error.message });
}
}
return {
tagIds: [...new Set(tagIds)], // Remove any duplicates
errors
};
} catch (error) {
console.error('[ERROR] in processTags:', error);
throw new Error(`[ERROR] Failed to process tags: ${error.message}`);
}
}
async getTags() {
this.initialize();
if (!this.client) {
console.error('[DEBUG] Client not initialized');
return [];
}
let tags = [];
let page = 1;
let hasMore = true;
while (hasMore) {
try {
const params = {
page,
page_size: 100, // Maximale Seitengröße für effizientes Laden
ordering: 'name' // Optional: Sortierung nach Namen
};
const response = await this.client.get('/tags/', { params });
if (!response?.data?.results || !Array.isArray(response.data.results)) {
console.error(`[DEBUG] Invalid API response on page ${page}`);
break;
}
tags = tags.concat(response.data.results);
hasMore = response.data.next !== null;
page++;
console.log(
`[DEBUG] Fetched page ${page-1}, got ${response.data.results.length} tags. ` +
`[DEBUG] Total so far: ${tags.length}`
);
// Kleine Verzögerung um die API nicht zu überlasten
await new Promise(resolve => setTimeout(resolve, 100));
} catch (error) {
console.error(`[ERRRO] fetching tags page ${page}:`, error.message);
if (error.response) {
console.error('[DEBUG] Response status:', error.response.status);
console.error('[DEBUG] Response data:', error.response.data);
}
break;
}
}
return tags;
}
async getTagCount() {
this.initialize();
try {
const response = await this.client.get('/tags/', {
params: { count: true }
});
return response.data.count;
} catch (error) {
console.error('[ERROR] fetching tag count:', error.message);
return 0;
}
}
async getCorrespondentCount() {
this.initialize();
try {
const response = await this.client.get('/correspondents/', {
params: { count: true }
});
return response.data.count;
} catch (error) {
console.error('[ERROR] fetching correspondent count:', error.message);
return 0;
}
}
async getDocumentCount() {
this.initialize();
try {
const response = await this.client.get('/documents/', {
params: { count: true }
});
return response.data.count;
} catch (error) {
console.error('[ERROR] fetching document count:', error.message);
return 0;
}
}
async listCorrespondentsNames() {
this.initialize();
let allCorrespondents = [];
let page = 1;
let hasNextPage = true;
try {
while (hasNextPage) {
const response = await this.client.get('/correspondents/', {
params: {
fields: 'id,name',
count: true,
page: page
}
});
const { results, next } = response.data;
// Füge die Ergebnisse der aktuellen Seite hinzu
allCorrespondents = allCorrespondents.concat(
results.map(correspondent => ({
name: correspondent.name,
id: correspondent.id,
document_count: correspondent.document_count
}))
);
// Prüfe, ob es eine nächste Seite gibt
hasNextPage = next !== null;
page++;
// Optional: Füge eine kleine Verzögerung hinzu, um die API nicht zu überlasten
if (hasNextPage) {
await new Promise(resolve => setTimeout(resolve, 100));
}
}
return allCorrespondents;
} catch (error) {
console.error('[ERROR] fetching correspondent names:', error.message);
return [];
}
}
async listTagNames() {
this.initialize();
let allTags = [];
let currentPage = 1;
let hasMorePages = true;
try {
while (hasMorePages) {
const response = await this.client.get('/tags/', {
params: {
fields: 'name',
count: true,
page: currentPage,
page_size: 100 // Sie können die Seitengröße nach Bedarf anpassen
}
});
// Füge die Tags dieser Seite zum Gesamtergebnis hinzu
allTags = allTags.concat(
response.data.results.map(tag => ({
name: tag.name,
document_count: tag.document_count
}))
);
// Prüfe, ob es weitere Seiten gibt
hasMorePages = response.data.next !== null;
currentPage++;
}
return allTags;
} catch (error) {
console.error('[DEBUG] Error fetching tag names:', error.message);
return [];
}
}
async getAllDocuments() {
this.initialize();
if (!this.client) {
console.error('[DEBUG] Client not initialized');
return [];
}
let documents = [];
let page = 1;
let hasMore = true;
const shouldFilterByTags = process.env.PROCESS_PREDEFINED_DOCUMENTS === 'yes';
let tagIds = [];
// Vorverarbeitung der Tags, wenn Filter aktiv ist
if (shouldFilterByTags) {
if (!process.env.TAGS) {
console.warn('[DEBUG] PROCESS_PREDEFINED_DOCUMENTS is set to yes but no TAGS are defined');
return [];
}
// Hole die Tag-IDs für die definierten Tags
const tagNames = process.env.TAGS.split(',').map(tag => tag.trim());
await this.ensureTagCache();
for (const tagName of tagNames) {
const tag = await this.findExistingTag(tagName);
if (tag) {
tagIds.push(tag.id);
}
}
if (tagIds.length === 0) {
console.warn('[DEBUG] None of the specified tags were found');
return [];
}
console.log('[DEBUG] Filtering documents for tag IDs:', tagIds);
}
while (hasMore) {
try {
const params = {
page,
page_size: 100,
fields: 'id,title,created,created_date,added,tags,correspondent'
};
// Füge Tag-Filter hinzu, wenn Tags definiert sind
if (shouldFilterByTags && tagIds.length > 0) {
// Füge jeden Tag-ID als separaten Parameter hinzu
tagIds.forEach(id => {
// Verwende tags__id__in für multiple Tag-Filterung
params.tags__id__in = tagIds.join(',');
});
}
const response = await this.client.get('/documents/', { params });
if (!response?.data?.results || !Array.isArray(response.data.results)) {
console.error(`[DEBUG] Invalid API response on page ${page}`);
break;
}
documents = documents.concat(response.data.results);
hasMore = response.data.next !== null;
page++;
console.log(
`[DEBUG] Fetched page ${page-1}, got ${response.data.results.length} documents. ` +
`[DEBUG] Total so far: ${documents.length}`
);
// Kleine Verzögerung um die API nicht zu überlasten
await new Promise(resolve => setTimeout(resolve, 100));
} catch (error) {
console.error(`[ERROR] fetching documents page ${page}:`, error.message);
if (error.response) {
console.error('[ERROR] Response status:', error.response.status);
}
break;
}
}
console.log(`[DEBUG] Finished fetching. Found ${documents.length} documents.`);
return documents;
}
async getAllDocumentIds() {
/**
* Get all Document IDs from the Paperless API.
*
* @returns An array of all Document IDs.
* @throws An error if the request fails.
* @note This method is used to get all Document IDs for further processing.
*/
this.initialize();
try {
const response = await this.client.get('/documents/', {
params: {
page,
page_size: 100,
fields: 'id',
}
});
return response.data.results.map(doc => doc.id);
} catch (error) {
console.error('[ERROR] fetching document IDs:', error.message);
return [];
}
}
async getAllDocumentIdsScan() {
/**
* Get all Document IDs from the Paperless API.
*
* @returns An array of all Document IDs.
* @throws An error if the request fails.
* @note This method is used to get all Document IDs for further processing.
*/
this.initialize();
if (!this.client) {
console.error('[DEBUG] Client not initialized');
return [];
}
let documents = [];
let page = 1;
let hasMore = true;
const shouldFilterByTags = process.env.PROCESS_PREDEFINED_DOCUMENTS === 'yes';
let tagIds = [];
// Vorverarbeitung der Tags, wenn Filter aktiv ist
if (shouldFilterByTags) {
if (!process.env.TAGS) {
console.warn('[DEBUG] PROCESS_PREDEFINED_DOCUMENTS is set to yes but no TAGS are defined');
return [];
}
// Hole die Tag-IDs für die definierten Tags
const tagNames = process.env.TAGS.split(',').map(tag => tag.trim());
await this.ensureTagCache();
for (const tagName of tagNames) {
const tag = await this.findExistingTag(tagName);
if (tag) {
tagIds.push(tag.id);
}
}
if (tagIds.length === 0) {
console.warn('[DEBUG] None of the specified tags were found');
return [];
}
console.log('[DEBUG] Filtering documents for tag IDs:', tagIds);
}
while (hasMore) {
try {
const params = {
page,
page_size: 100,
fields: 'id'
};
const response = await this.client.get('/documents/', { params });
if (!response?.data?.results || !Array.isArray(response.data.results)) {
console.error(`[ERROR] Invalid API response on page ${page}`);
break;
}
documents = documents.concat(response.data.results);
hasMore = response.data.next !== null;
page++;
console.log(
`[DEBUG] Fetched page ${page-1}, got ${response.data.results.length} documents. ` +
`[DEBUG] Total so far: ${documents.length}`
);
// Kleine Verzögerung um die API nicht zu überlasten
await new Promise(resolve => setTimeout(resolve, 100));
} catch (error) {
console.error(`[ERROR] fetching documents page ${page}:`, error.message);
if (error.response) {
console.error('[DEBUG] Response status:', error.response.status);
}
break;
}
}
console.log(`[DEBUG] Finished fetching. Found ${documents.length} documents.`);
return documents;
}
async getCorrespondentNameById(correspondentId) {
/**
* Get the Name of a Correspondent by its ID.
*
* @param id The id of the correspondent.
* @returns The name of the correspondent.
*/
this.initialize();
try {
const response = await this.client.get(`/correspondents/${correspondentId}/`);
return response.data;
} catch (error) {
console.error(`[ERROR] fetching correspondent ${correspondentId}:`, error.message);
return null;
}
}
async getTagNameById(tagId) {
/**
* Get the Name of a Tag by its ID.
*
* @param id The id of the tag.
* @returns The name of the tag.
*/
this.initialize();
try {
const response = await this.client.get(`/tags/${tagId}/`);
return response.data.name;
} catch (error) {
console.error(`[ERROR] fetching tag name for ID ${tagId}:`, error.message);
return null;
}
}
async getDocumentsWithTitleTagsCorrespondentCreated () {
/**
* Get all documents with metadata (title, tags, correspondent, created date).
*
* @returns An array of documents with metadata.
* @throws An error if the request fails.
* @note This method is used to get all documents with metadata for further processing
*/
this.initialize();
try {
const response = await this.client.get('/documents/', {
params: {
fields: 'id,title,tags,correspondent,created'
}
});
return response.data.results;
} catch (error) {
console.error('[ERROR] fetching documents with metadata:', error.message);
return [];
}
}
async getDocumentsForRAGService () {
/**
* Get all documents with metadata (title, tags, correspondent, created date and content).
*
* @returns An array of documents with metadata.
* @throws An error if the request fails.
* @note This method is used to get all documents with metadata for further processing
*/
this.initialize();
try {
let response;
let page = 1;
let hasMore = true;
while (hasMore) {
try {
const params = {
params: { fields: 'id,title,tags,correspondent,created,content' },
page,
page_size: 100, // Maximale Seitengröße für effizientes Laden
ordering: 'name' // Optional: Sortierung nach Namen
};
response = await this.client.get('/documents/', { params });
if (!response?.data?.results || !Array.isArray(response.data.results)) {
console.error(`[DEBUG] Invalid API response on page ${page}`);
break;
}
hasMore = response.data.next !== null;
page++;
} catch (error) {
console.error(`[ERROR] fetching documents page ${page}:`, error.message);
if (error.response) {
console.error('[ERROR] Response status:', error.response.status);
}
break;
}
}
return response.data.results;
} catch (error) {
console.error('[ERROR] fetching documents with metadata:', error.message);
return [];
}
}
// Aktualisierte getDocuments Methode
async getDocuments() {
return this.getAllDocuments();
}
async getDocumentContent(documentId) {
this.initialize();
const response = await this.client.get(`/documents/${documentId}/`);
return response.data.content;
}
async getDocument(documentId) {
this.initialize();
try {
const response = await this.client.get(`/documents/${documentId}/`);
return response.data;
} catch (error) {
console.error(`[ERROR] fetching document ${documentId}:`, error.message);
throw error;
}
}
async searchForCorrespondentById(id) {
try {
const response = await this.client.get('/correspondents/', {
params: {
id: id
}
});
const results = response.data.results;
if (results.length === 0) {
console.log(`[DEBUG] No correspondent with "${id}" found`);
return null;
}
if (results.length > 1) {
console.log(`[DEBUG] Multiple correspondents found:`);
results.forEach(c => {
console.log(`- ID: ${c.id}, Name: ${c.name}`);
});
return results;
}
// Genau ein Ergebnis gefunden
return {
id: results[0].id,
name: results[0].name
};
} catch (error) {
console.error('[ERROR] while seraching for existing correspondent:', error.message);
throw error;
}
}
async searchForExistingCorrespondent(correspondent) {
try {
const response = await this.client.get('/correspondents/', {
params: {
name__icontains: correspondent
}
});
const results = response.data.results;
if (results.length === 0) {
console.log(`[DEBUG] No correspondent with name "${correspondent}" found`);
return null;
}
// Check for exact match in the results - thanks to @skius for the hint!
const exactMatch = results.find(c => c.name.toLowerCase() === correspondent.toLowerCase());
if (exactMatch) {
console.log(`[DEBUG] Found exact match for correspondent "${correspondent}" with ID ${exactMatch.id}`);
return {
id: exactMatch.id,
name: exactMatch.name
};
}
// No exact match found, return null
console.log(`[DEBUG] No exact match found for "${correspondent}"`);
return null;
} catch (error) {
console.error('[ERROR] while searching for existing correspondent:', error.message);
throw error;
}
}
async getOrCreateCorrespondent(name) {
this.initialize();
// Entferne nur Sonderzeichen, behalte Leerzeichen
// const sanitizedName = name.replace(/[.,]/g, '').trim();
// const normalizedName = sanitizedName.toLowerCase();
try {
// Suche mit dem bereinigten Namen
const existingCorrespondent = await this.searchForExistingCorrespondent(name);
console.log("[DEBUG] Response Correspondent Search: ", existingCorrespondent);
if (existingCorrespondent) {
console.log(`[DEBUG] Found existing correspondent "${name}" with ID ${existingCorrespondent.id}`);
return existingCorrespondent;
}
// Erstelle neuen Korrespondenten
try {
const createResponse = await this.client.post('/correspondents/', {
name: name
});
console.log(`[DEBUG] Created new correspondent "${name}" with ID ${createResponse.data.id}`);
return createResponse.data;
} catch (createError) {
if (createError.response?.status === 400 &&
createError.response?.data?.error?.includes('unique constraint')) {
// Race condition check
const retryResponse = await this.client.get('/correspondents/', {
params: { name: name }
});
const justCreatedCorrespondent = retryResponse.data.results.find(
c => c.name.toLowerCase() === normalizedName
);
if (justCreatedCorrespondent) {
console.log(`[DEBUG] Retrieved correspondent "${name}" after constraint error with ID ${justCreatedCorrespondent.id}`);
return justCreatedCorrespondent;
}
}
throw createError;
}
} catch (error) {
console.error(`[ERROR] Failed to process correspondent "${name}":`, error.message);
throw error;
}
}
async searchForExistingDocumentType(documentType) {
try {
const response = await this.client.get('/document_types/', {
params: {
name__icontains: documentType
}
});
const results = response.data.results;
if (results.length === 0) {
console.log(`[DEBUG] No document type with name "${documentType}" found`);
return null;
}
// Check for exact match in the results
const exactMatch = results.find(dt => dt.name.toLowerCase() === documentType.toLowerCase());
if (exactMatch) {
console.log(`[DEBUG] Found exact match for document type "${documentType}" with ID ${exactMatch.id}`);
return {
id: exactMatch.id,
name: exactMatch.name
};
}
// No exact match found, return null
console.log(`[DEBUG] No exact match found for "${documentType}"`);
return null;
} catch (error) {
console.error('[ERROR] while searching for existing document type:', error.message);
throw error;
}
}
async getOrCreateDocumentType(name) {
this.initialize();
try {
// Suche nach existierendem document_type
const existingDocType = await this.searchForExistingDocumentType(name);
console.log("[DEBUG] Response Document Type Search: ", existingDocType);
if (existingDocType) {
console.log(`[DEBUG] Found existing document type "${name}" with ID ${existingDocType.id}`);