Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

feat(documents): added deleted and total metrics in the organization stats route (#556)

Corentin Thomassetf66a9f5d1b3f
diff --git a/.changeset/cyan-beds-retire.md b/.changeset/cyan-beds-retire.md
new file mode 100644
index 00000000..726065bc
--- /dev/null
+++ b/.changeset/cyan-beds-retire.md
@@ -0,0 +1,5 @@
+---
+"@papra/docker": patch
+---
+
+Added deleted and total document counts and sizes in the `/api/organizations/:organizationId/documents/statistics` route
diff --git a/apps/papra-client/src/modules/documents/documents.services.ts b/apps/papra-client/src/modules/documents/documents.services.ts
index 77ee02d4..c4b73300 100644
--- a/apps/papra-client/src/modules/documents/documents.services.ts
+++ b/apps/papra-client/src/modules/documents/documents.services.ts
@@ -168,7 +168,16 @@ export async function searchDocuments({
}
export async function getOrganizationDocumentsStats({ organizationId }: { organizationId: string }) {
- const { organizationStats } = await apiClient<{ organizationStats: { documentsCount: number; documentsSize: number } }>({
+ const { organizationStats } = await apiClient<{
+ organizationStats: {
+ documentsCount: number;
+ documentsSize: number;
+ deletedDocumentsSize: number;
+ deletedDocumentsCount: number;
+ totalDocumentsCount: number;
+ totalDocumentsSize: number;
+ };
+ }>({
method: 'GET',
path: `/api/organizations/${organizationId}/documents/statistics`,
});
diff --git a/apps/papra-client/src/modules/subscriptions/subscriptions.services.ts b/apps/papra-client/src/modules/subscriptions/subscriptions.services.ts
index 1b2286ab..839a9020 100644
--- a/apps/papra-client/src/modules/subscriptions/subscriptions.services.ts
+++ b/apps/papra-client/src/modules/subscriptions/subscriptions.services.ts
@@ -43,7 +43,7 @@ export async function fetchOrganizationSubscription({ organizationId }: { organi
export async function fetchOrganizationUsage({ organizationId }: { organizationId: string }) {
const { usage, limits } = await apiClient<{
usage: {
- documentsStorage: { used: number; limit: number | null };
+ documentsStorage: { used: number; deleted: number; limit: number | null };
intakeEmailsCount: { used: number; limit: number | null };
membersCount: { used: number; limit: number | null };
};
diff --git a/apps/papra-server/src/modules/documents/documents.repository.test.ts b/apps/papra-server/src/modules/documents/documents.repository.test.ts
index 2e19b96a..126094b5 100644
--- a/apps/papra-server/src/modules/documents/documents.repository.test.ts
+++ b/apps/papra-server/src/modules/documents/documents.repository.test.ts
@@ -155,6 +155,8 @@ describe('documents repository', () => {
{ id: 'doc-2', organizationId: 'organization-1', createdBy: 'user-1', name: 'File 2', originalName: 'document-2.pdf', content: 'lorem', originalStorageKey: '', mimeType: 'application/pdf', originalSize: 10, originalSha256Hash: 'hash2' },
{ id: 'doc-3', organizationId: 'organization-1', createdBy: 'user-1', name: 'File 3', originalName: 'document-3.pdf', content: 'ipsum', originalStorageKey: '', mimeType: 'application/pdf', originalSize: 5, originalSha256Hash: 'hash3' },
{ id: 'doc-4', organizationId: 'organization-2', createdBy: 'user-2', name: 'File 3', originalName: 'document-3.pdf', content: 'ipsum', originalStorageKey: '', mimeType: 'application/pdf', originalSize: 100, originalSha256Hash: 'hash4' },
+ { id: 'doc-5', organizationId: 'organization-1', createdBy: 'user-2', name: 'File 3', originalName: 'document-3.pdf', content: 'ipsum', originalStorageKey: '', mimeType: 'application/pdf', originalSize: 100, originalSha256Hash: 'hash5', deletedAt: new Date(0), isDeleted: true },
+ { id: 'doc-6', organizationId: 'organization-1', createdBy: 'user-2', name: 'File 3', originalName: 'document-3.pdf', content: 'ipsum', originalStorageKey: '', mimeType: 'application/pdf', originalSize: 100, originalSha256Hash: 'hash6', deletedAt: new Date(0), isDeleted: true },
],
});
@@ -167,6 +169,10 @@ describe('documents repository', () => {
expect(stats).to.deep.equal({
documentsCount: 3,
documentsSize: 215,
+ totalDocumentsSize: 415,
+ totalDocumentsCount: 5,
+ deletedDocumentsCount: 2,
+ deletedDocumentsSize: 200,
});
});
@@ -192,6 +198,10 @@ describe('documents repository', () => {
expect(stats).to.deep.equal({
documentsCount: 0,
documentsSize: 0,
+ totalDocumentsSize: 0,
+ totalDocumentsCount: 0,
+ deletedDocumentsCount: 0,
+ deletedDocumentsSize: 0,
});
});
@@ -207,6 +217,10 @@ describe('documents repository', () => {
expect(stats).to.deep.equal({
documentsCount: 0,
documentsSize: 0,
+ totalDocumentsSize: 0,
+ totalDocumentsCount: 0,
+ deletedDocumentsCount: 0,
+ deletedDocumentsSize: 0,
});
});
});
diff --git a/apps/papra-server/src/modules/documents/documents.repository.ts b/apps/papra-server/src/modules/documents/documents.repository.ts
index 15e796d9..545cc40f 100644
--- a/apps/papra-server/src/modules/documents/documents.repository.ts
+++ b/apps/papra-server/src/modules/documents/documents.repository.ts
@@ -2,7 +2,7 @@ import type { Database } from '../app/database/database.types';
import type { DbInsertableDocument } from './documents.types';
import { injectArguments, safely } from '@corentinth/chisels';
import { subDays } from 'date-fns';
-import { and, count, desc, eq, getTableColumns, lt, sql, sum } from 'drizzle-orm';
+import { and, count, desc, eq, getTableColumns, lt, sql } from 'drizzle-orm';
import { omit } from 'lodash-es';
import { createIterator } from '../app/database/database.usecases';
import { createOrganizationNotFoundError } from '../organizations/organizations.errors';
@@ -332,14 +332,17 @@ async function searchOrganizationDocuments({ organizationId, searchQuery, pageIn
async function getOrganizationStats({ organizationId, db }: { organizationId: string; db: Database }) {
const [record] = await db
.select({
- documentsCount: count(documentsTable.id),
- documentsSize: sum(documentsTable.originalSize),
+ totalDocumentsCount: count(documentsTable.id),
+ totalDocumentsSize: sql<number>`COALESCE(SUM(${documentsTable.originalSize}), 0)`.as('totalDocumentsSize'),
+ deletedDocumentsCount: sql<number>`COUNT(${documentsTable.id}) FILTER (WHERE ${documentsTable.isDeleted} = true)`.as('deletedDocumentsCount'),
+ documentsCount: sql<number>`COUNT(${documentsTable.id}) FILTER (WHERE ${documentsTable.isDeleted} = false)`.as('documentsCount'),
+ documentsSize: sql<number>`COALESCE(SUM(${documentsTable.originalSize}) FILTER (WHERE ${documentsTable.isDeleted} = false), 0)`.as('documentsSize'),
+ deletedDocumentsSize: sql<number>`COALESCE(SUM(${documentsTable.originalSize}) FILTER (WHERE ${documentsTable.isDeleted} = true), 0)`.as('deletedDocumentsSize'),
})
.from(documentsTable)
.where(
and(
eq(documentsTable.organizationId, organizationId),
- eq(documentsTable.isDeleted, false),
),
);
@@ -347,11 +350,15 @@ async function getOrganizationStats({ organizationId, db }: { organizationId: st
throw createOrganizationNotFoundError();
}
- const { documentsCount, documentsSize } = record;
+ const { documentsCount, documentsSize, deletedDocumentsCount, deletedDocumentsSize, totalDocumentsCount, totalDocumentsSize } = record;
return {
documentsCount,
documentsSize: Number(documentsSize ?? 0),
+ deletedDocumentsCount,
+ deletedDocumentsSize,
+ totalDocumentsCount,
+ totalDocumentsSize,
};
}
diff --git a/apps/papra-server/src/modules/documents/documents.routes.ts b/apps/papra-server/src/modules/documents/documents.routes.ts
index 701113bd..1d3df866 100644
--- a/apps/papra-server/src/modules/documents/documents.routes.ts
+++ b/apps/papra-server/src/modules/documents/documents.routes.ts
@@ -352,12 +352,23 @@ function setupGetOrganizationDocumentsStatsRoute({ app, db }: RouteDefinitionCon
await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });
- const { documentsCount, documentsSize } = await documentsRepository.getOrganizationStats({ organizationId });
+ const {
+ documentsCount,
+ documentsSize,
+ deletedDocumentsCount,
+ deletedDocumentsSize,
+ totalDocumentsCount,
+ totalDocumentsSize,
+ } = await documentsRepository.getOrganizationStats({ organizationId });
return context.json({
organizationStats: {
documentsCount,
documentsSize,
+ deletedDocumentsCount,
+ deletedDocumentsSize,
+ totalDocumentsCount,
+ totalDocumentsSize,
},
});
},
diff --git a/apps/papra-server/src/modules/organizations/organizations.usecases.test.ts b/apps/papra-server/src/modules/organizations/organizations.usecases.test.ts
index afeebe33..70bd21f6 100644
--- a/apps/papra-server/src/modules/organizations/organizations.usecases.test.ts
+++ b/apps/papra-server/src/modules/organizations/organizations.usecases.test.ts
@@ -7,15 +7,14 @@ import { createForbiddenError } from '../app/auth/auth.errors';
import { createInMemoryDatabase } from '../app/database/database.test-utils';
import { overrideConfig } from '../config/config.test-utils';
import { createDocumentsRepository } from '../documents/documents.repository';
-import { PLUS_PLAN_ID } from '../plans/plans.constants';
import { createTestLogger } from '../shared/logger/logger.test-utils';
import { createSubscriptionsRepository } from '../subscriptions/subscriptions.repository';
import { createUsersRepository } from '../users/users.repository';
import { ORGANIZATION_ROLES } from './organizations.constants';
-import { createMaxOrganizationMembersCountReachedError, createOrganizationDocumentStorageLimitReachedError, createOrganizationInvitationAlreadyExistsError, createOrganizationNotFoundError, createUserAlreadyInOrganizationError, createUserMaxOrganizationCountReachedError, createUserNotInOrganizationError, createUserNotOrganizationOwnerError, createUserOrganizationInvitationLimitReachedError } from './organizations.errors';
+import { createMaxOrganizationMembersCountReachedError, createOrganizationInvitationAlreadyExistsError, createOrganizationNotFoundError, createUserAlreadyInOrganizationError, createUserMaxOrganizationCountReachedError, createUserNotInOrganizationError, createUserNotOrganizationOwnerError, createUserOrganizationInvitationLimitReachedError } from './organizations.errors';
import { createOrganizationsRepository } from './organizations.repository';
import { organizationInvitationsTable, organizationMembersTable, organizationsTable } from './organizations.table';
-import { checkIfOrganizationCanCreateNewDocument, checkIfUserCanCreateNewOrganization, ensureUserIsInOrganization, ensureUserIsOwnerOfOrganization, getOrCreateOrganizationCustomerId, inviteMemberToOrganization, purgeExpiredSoftDeletedOrganization, purgeExpiredSoftDeletedOrganizations, removeMemberFromOrganization, softDeleteOrganization } from './organizations.usecases';
+import { checkIfUserCanCreateNewOrganization, ensureUserIsInOrganization, ensureUserIsOwnerOfOrganization, getOrCreateOrganizationCustomerId, inviteMemberToOrganization, purgeExpiredSoftDeletedOrganization, purgeExpiredSoftDeletedOrganizations, removeMemberFromOrganization, softDeleteOrganization } from './organizations.usecases';
describe('organizations usecases', () => {
describe('ensureUserIsInOrganization', () => {
@@ -158,76 +157,6 @@ describe('organizations usecases', () => {
});
});
- describe('checkIfOrganizationCanCreateNewDocument', () => {
- test('it is possible to create a new document if the organization has enough allowed storage space defined in the organization plan', async () => {
- const { db } = await createInMemoryDatabase({
- users: [{ id: 'user-1', email: '[email protected]' }],
- organizations: [{ id: 'organization-1', name: 'Organization 1' }],
- organizationMembers: [{ organizationId: 'organization-1', userId: 'user-1', role: ORGANIZATION_ROLES.OWNER }],
- organizationSubscriptions: [{
- id: 'org_sub_1',
- organizationId: 'organization-1',
- planId: PLUS_PLAN_ID,
- seatsCount: 10,
- customerId: 'cus_123',
- status: 'active',
- currentPeriodStart: new Date('2025-03-18T00:00:00.000Z'),
- currentPeriodEnd: new Date('2025-04-18T00:00:00.000Z'),
- cancelAtPeriodEnd: false,
- }],
- documents: [{
- id: 'doc_1',
- organizationId: 'organization-1',
- originalSize: 100,
- mimeType: 'text/plain',
- originalName: 'test.txt',
- originalStorageKey: 'test.txt',
- originalSha256Hash: '123',
- name: 'test.txt',
- }],
- });
-
- const plansRepository = {
- getOrganizationPlanById: async () => ({
- organizationPlan: {
- id: PLUS_PLAN_ID,
- name: 'Plus',
- limits: {
- maxDocumentStorageBytes: 512,
- maxIntakeEmailsCount: 10,
- maxOrganizationsMembersCount: 100,
- },
- },
- }),
- } as unknown as PlansRepository;
-
- const subscriptionsRepository = createSubscriptionsRepository({ db });
- const documentsRepository = createDocumentsRepository({ db });
-
- // no throw as the document size is less than the allowed storage space
- await checkIfOrganizationCanCreateNewDocument({
- organizationId: 'organization-1',
- newDocumentSize: 100,
- documentsRepository,
- plansRepository,
- subscriptionsRepository,
- });
-
- // throw as the document size is greater than the allowed storage space
- await expect(
- checkIfOrganizationCanCreateNewDocument({
- organizationId: 'organization-1',
- newDocumentSize: 413,
- documentsRepository,
- plansRepository,
- subscriptionsRepository,
- }),
- ).rejects.toThrow(
- createOrganizationDocumentStorageLimitReachedError(),
- );
- });
- });
-
describe('getOrCreateOrganizationCustomerId', () => {
describe(`in order to handle organization subscriptions, we need a stripe customer id per organization
as stripe require an email per customer, we use the organization owner's email`, () => {
diff --git a/apps/papra-server/src/modules/organizations/organizations.usecases.ts b/apps/papra-server/src/modules/organizations/organizations.usecases.ts
index 35f21f5b..fef2fc94 100644
--- a/apps/papra-server/src/modules/organizations/organizations.usecases.ts
+++ b/apps/papra-server/src/modules/organizations/organizations.usecases.ts
@@ -21,7 +21,6 @@ import { ORGANIZATION_INVITATION_STATUS, ORGANIZATION_ROLES } from './organizati
import {
createMaxOrganizationMembersCountReachedError,
createOnlyPreviousOwnerCanRestoreError,
- createOrganizationDocumentStorageLimitReachedError,
createOrganizationInvitationAlreadyExistsError,
createOrganizationNotDeletedError,
createOrganizationNotFoundError,
@@ -82,28 +81,6 @@ export async function checkIfUserCanCreateNewOrganization({
}
}
-export async function checkIfOrganizationCanCreateNewDocument({
- organizationId,
- newDocumentSize,
- plansRepository,
- subscriptionsRepository,
- documentsRepository,
-}: {
- organizationId: string;
- newDocumentSize: number;
- plansRepository: PlansRepository;
- subscriptionsRepository: SubscriptionsRepository;
- documentsRepository: DocumentsRepository;
-}) {
- const { organizationPlan } = await getOrganizationPlan({ organizationId, subscriptionsRepository, plansRepository });
-
- const { documentsSize } = await documentsRepository.getOrganizationStats({ organizationId });
-
- if (documentsSize + newDocumentSize > organizationPlan.limits.maxDocumentStorageBytes) {
- throw createOrganizationDocumentStorageLimitReachedError();
- }
-}
-
export async function getOrCreateOrganizationCustomerId({
organizationId,
subscriptionsServices,
@@ -460,7 +437,7 @@ export async function getOrganizationStorageLimits({
}) {
const [
{ organizationPlan },
- { documentsSize },
+ { totalDocumentsSize },
] = await Promise.all([
getOrganizationPlan({ organizationId, subscriptionsRepository, plansRepository }),
documentsRepository.getOrganizationStats({ organizationId }),
@@ -469,7 +446,7 @@ export async function getOrganizationStorageLimits({
const { maxDocumentStorageBytes, maxFileSize } = organizationPlan.limits;
return {
- availableDocumentStorageBytes: maxDocumentStorageBytes - documentsSize,
+ availableDocumentStorageBytes: maxDocumentStorageBytes - totalDocumentsSize,
maxDocumentStorageBytes,
maxFileSize,
};
diff --git a/apps/papra-server/src/modules/subscriptions/subscriptions.routes.ts b/apps/papra-server/src/modules/subscriptions/subscriptions.routes.ts
index 67d4a6af..f829ab3e 100644
--- a/apps/papra-server/src/modules/subscriptions/subscriptions.routes.ts
+++ b/apps/papra-server/src/modules/subscriptions/subscriptions.routes.ts
@@ -217,7 +217,7 @@ function setupGetOrganizationSubscriptionUsageRoute({ app, db, config }: RouteDe
const [
{ organizationPlan },
- { documentsSize },
+ { totalDocumentsSize, deletedDocumentsSize },
{ intakeEmailCount },
{ membersCount },
] = await Promise.all([
@@ -237,7 +237,8 @@ function setupGetOrganizationSubscriptionUsageRoute({ app, db, config }: RouteDe
return context.json({
usage: {
documentsStorage: {
- used: documentsSize,
+ used: totalDocumentsSize,
+ deleted: deletedDocumentsSize,
limit: nullifiedLimits.maxDocumentStorageBytes,
},
intakeEmailsCount: {