3 Commits

Author SHA1 Message Date
a7895ad394 Release v0.1.3 2026-06-26 01:39:18 +02:00
189e950589 Release v0.1.2 2026-06-25 19:58:20 +02:00
b5f7c43028 Fix WebUI release peer metadata 2026-06-24 20:17:20 +02:00
15 changed files with 478 additions and 101 deletions

37
AGENTS.md Normal file
View File

@@ -0,0 +1,37 @@
# GovOPlaN Files Codex Guide
## Scope
This repository owns the `files` module: managed file storage APIs, file metadata, shares, uploads/downloads, folder and pattern helpers, backend module manifest, and `@govoplan/files-webui`.
Core owns auth, tenants, RBAC, database/session primitives, CSRF/API helpers, shared components, and shell layout. Campaign integration must remain optional and go through core module metadata or capabilities.
## Local Commands
Install and run through core:
```bash
cd /mnt/DATA/git/govoplan-core
./.venv/bin/python -m pip install -r requirements-dev.txt
```
For combined checks, run:
```bash
cd /mnt/DATA/git/govoplan-core
./scripts/check-focused.sh
```
For WebUI permutation checks that include files:
```bash
cd /mnt/DATA/git/govoplan-core/webui
PATH=/mnt/DATA/git/govoplan-core/webui/node_modules/.bin:/home/zemion/.nvm/versions/node/v22.22.3/bin:$PATH /home/zemion/.nvm/versions/node/v22.22.3/bin/npm run test:module-permutations
```
## Working Rules
- Keep files behavior in this module, not core.
- Do not require campaign or mail imports for files-only startup.
- Shared WebUI components belong in core; files WebUI should consume them through `@govoplan/core-webui`.
- Preserve optional campaign usage tracking through capability/registry boundaries.

View File

@@ -1,6 +1,6 @@
{ {
"name": "@govoplan/files-webui", "name": "@govoplan/files-webui",
"version": "0.1.0", "version": "0.1.1",
"private": true, "private": true,
"type": "module", "type": "module",
"main": "webui/src/index.ts", "main": "webui/src/index.ts",
@@ -19,7 +19,7 @@
"LICENSE" "LICENSE"
], ],
"peerDependencies": { "peerDependencies": {
"@govoplan/core-webui": "^0.1.0", "@govoplan/core-webui": "^0.1.1",
"lucide-react": "^0.555.0", "lucide-react": "^0.555.0",
"react": "^19.0.0", "react": "^19.0.0",
"react-dom": "^19.0.0", "react-dom": "^19.0.0",
@@ -27,5 +27,10 @@
"@vitejs/plugin-react": "^4.3.4", "@vitejs/plugin-react": "^4.3.4",
"typescript": "^5.7.2", "typescript": "^5.7.2",
"vite": "^6.0.6" "vite": "^6.0.6"
},
"peerDependenciesMeta": {
"@govoplan/core-webui": {
"optional": true
}
} }
} }

View File

@@ -4,14 +4,14 @@ build-backend = "setuptools.build_meta"
[project] [project]
name = "govoplan-files" name = "govoplan-files"
version = "0.1.0" version = "0.1.3"
description = "GovOPlaN files module with backend and WebUI integration." description = "GovOPlaN files module with backend and WebUI integration."
readme = "README.md" readme = "README.md"
requires-python = ">=3.12" requires-python = ">=3.12"
license = { file = "LICENSE" } license = { file = "LICENSE" }
authors = [{ name = "GovOPlaN" }] authors = [{ name = "GovOPlaN" }]
dependencies = [ dependencies = [
"govoplan-core>=0.1.0", "govoplan-core>=0.1.3",
] ]
[tool.setuptools.packages.find] [tool.setuptools.packages.find]

View File

@@ -0,0 +1,34 @@
from __future__ import annotations
from typing import Any
from govoplan_core.core.modules import ModuleContext
from govoplan_files.backend.runtime import configure_runtime
from govoplan_files.backend.storage.campaign_attachments import (
annotate_built_messages_with_managed_files,
managed_match_payloads,
prepared_campaign_snapshot,
public_attachment_summary_payload,
)
from govoplan_files.backend.storage.campaign_usage import record_campaign_attachment_uses_for_jobs
from govoplan_files.backend.storage.files import current_version_and_blob
class FilesCampaignCapability:
prepared_campaign_snapshot = staticmethod(prepared_campaign_snapshot)
managed_match_payloads = staticmethod(managed_match_payloads)
public_attachment_summary_payload = staticmethod(public_attachment_summary_payload)
annotate_built_messages_with_managed_files = staticmethod(annotate_built_messages_with_managed_files)
record_campaign_attachment_uses_for_jobs = staticmethod(record_campaign_attachment_uses_for_jobs)
current_version_and_blob = staticmethod(current_version_and_blob)
@staticmethod
def mark_job_attachment_uses_sent(session: Any, job: Any) -> None:
from govoplan_files.backend.storage.campaign_usage import mark_job_attachment_uses_sent
mark_job_attachment_uses_sent(session, job)
def campaign_capability(context: ModuleContext) -> FilesCampaignCapability:
configure_runtime(settings=context.settings)
return FilesCampaignCapability()

View File

@@ -66,7 +66,7 @@ def _files_router(context: ModuleContext):
manifest = ModuleManifest( manifest = ModuleManifest(
id="files", id="files",
name="Files", name="Files",
version="1.0.0", version="0.1.2",
dependencies=("access",), dependencies=("access",),
optional_dependencies=(), optional_dependencies=(),
permissions=PERMISSIONS, permissions=PERMISSIONS,
@@ -83,9 +83,11 @@ manifest = ModuleManifest(
metadata=Base.metadata, metadata=Base.metadata,
script_location=str(Path(__file__).with_name("migrations") / "versions"), script_location=str(Path(__file__).with_name("migrations") / "versions"),
), ),
capability_factories={
"files.campaign_attachments": lambda context: __import__("govoplan_files.backend.capabilities", fromlist=["campaign_capability"]).campaign_capability(context),
},
) )
def get_manifest() -> ModuleManifest: def get_manifest() -> ModuleManifest:
return manifest return manifest

View File

@@ -13,8 +13,11 @@ from sqlalchemy import or_
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from govoplan_core.auth.dependencies import ApiPrincipal, has_scope, require_scope from govoplan_core.auth.dependencies import ApiPrincipal, has_scope, require_scope
from govoplan_core.core.optional import reraise_unless_missing_package
from govoplan_files.backend.schemas import ( from govoplan_files.backend.schemas import (
ArchiveRequest, ArchiveRequest,
BulkFileShareRequest,
BulkFileShareResponse,
BulkDeleteRequest, BulkDeleteRequest,
BulkDeleteResponse, BulkDeleteResponse,
ConflictResolutionRequest, ConflictResolutionRequest,
@@ -41,7 +44,6 @@ from govoplan_files.backend.schemas import (
_conflict_resolutions, _conflict_resolutions,
) )
from govoplan_core.db.models import Group, UserGroupMembership from govoplan_core.db.models import Group, UserGroupMembership
from govoplan_campaign.backend.db.models import Campaign, CampaignShare
from govoplan_files.backend.db.models import FileAsset, FileFolder, FileShare from govoplan_files.backend.db.models import FileAsset, FileFolder, FileShare
from govoplan_core.db.session import get_session from govoplan_core.db.session import get_session
from govoplan_files.backend.runtime import settings from govoplan_files.backend.runtime import settings
@@ -57,6 +59,7 @@ from govoplan_files.backend.storage.files import (
list_assets_for_user, list_assets_for_user,
read_asset_bytes, read_asset_bytes,
share_file, share_file,
share_files,
soft_delete_assets, soft_delete_assets,
) )
from govoplan_files.backend.storage.folders import create_folder, list_folders_for_user, soft_delete_folder from govoplan_files.backend.storage.folders import create_folder, list_folders_for_user, soft_delete_folder
@@ -66,6 +69,14 @@ from govoplan_files.backend.storage.transfers import rename_selection, transfer_
router = APIRouter(prefix="/files", tags=["files"]) router = APIRouter(prefix="/files", tags=["files"])
def _campaign_models():
try:
from govoplan_campaign.backend.db.models import Campaign, CampaignShare
except ModuleNotFoundError as exc:
reraise_unless_missing_package(exc, "govoplan_campaign")
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Campaign module is not installed") from exc
return Campaign, CampaignShare
def _is_admin(principal: ApiPrincipal) -> bool: def _is_admin(principal: ApiPrincipal) -> bool:
return has_scope(principal, "files:file:admin") return has_scope(principal, "files:file:admin")
@@ -105,6 +116,7 @@ def _ensure_campaign_file_access(session: Session, principal: ApiPrincipal, camp
return return
if not has_scope(principal, "campaigns:campaign:read"): if not has_scope(principal, "campaigns:campaign:read"):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Missing scope: campaign:read") raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Missing scope: campaign:read")
Campaign, CampaignShare = _campaign_models()
campaign = session.get(Campaign, campaign_id) campaign = session.get(Campaign, campaign_id)
if not campaign or campaign.tenant_id != principal.tenant_id: if not campaign or campaign.tenant_id != principal.tenant_id:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Campaign not found") raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Campaign not found")
@@ -538,6 +550,48 @@ def create_share(
raise _http_error(exc) from exc raise _http_error(exc) from exc
@router.post("/bulk-shares", response_model=BulkFileShareResponse)
def create_bulk_shares(
payload: BulkFileShareRequest,
session: Session = Depends(get_session),
principal: ApiPrincipal = Depends(require_scope("files:file:share")),
):
try:
file_ids = list(dict.fromkeys(payload.file_ids))
assets = [
get_asset_for_user(session, tenant_id=principal.tenant_id, user_id=principal.user.id, asset_id=file_id, require_write=True, is_admin=_is_admin(principal))
for file_id in file_ids
]
shares = share_files(
session,
tenant_id=principal.tenant_id,
assets=assets,
target_type=payload.target_type,
target_id=payload.target_id,
permission=payload.permission,
user_id=principal.user.id,
)
session.commit()
return BulkFileShareResponse(
shared_count=len(shares),
shares=[
FileShareResponse(
id=share.id,
target_type=share.target_type,
target_id=share.target_id,
permission=share.permission,
created_at=share.created_at.isoformat(),
revoked_at=share.revoked_at.isoformat() if share.revoked_at else None,
)
for share in shares
],
)
except FileStorageError as exc:
session.rollback()
raise _http_error(exc) from exc
@router.post("/bulk-rename", response_model=RenameResponse) @router.post("/bulk-rename", response_model=RenameResponse)
def bulk_rename( def bulk_rename(
payload: RenameRequest, payload: RenameRequest,

View File

@@ -113,6 +113,18 @@ class FileShareRequest(BaseModel):
permission: Literal["read", "write", "manage"] = "read" permission: Literal["read", "write", "manage"] = "read"
class BulkFileShareRequest(BaseModel):
file_ids: list[str] = Field(default_factory=list, max_length=1000)
target_type: Literal["user", "group", "campaign", "tenant"]
target_id: str
permission: Literal["read", "write", "manage"] = "read"
class BulkFileShareResponse(BaseModel):
shares: list[FileShareResponse]
shared_count: int
class RenameRequest(BaseModel): class RenameRequest(BaseModel):
file_ids: list[str] = Field(default_factory=list) file_ids: list[str] = Field(default_factory=list)
folder_paths: list[str] = Field(default_factory=list) folder_paths: list[str] = Field(default_factory=list)

View File

@@ -4,8 +4,6 @@ from dataclasses import dataclass, field
from pathlib import Path from pathlib import Path
from typing import Iterable, Protocol from typing import Iterable, Protocol
import boto3
from govoplan_files.backend.runtime import settings from govoplan_files.backend.runtime import settings
@@ -94,6 +92,10 @@ class S3StorageBackend:
@property @property
def client(self): def client(self):
try:
import boto3
except ModuleNotFoundError as exc:
raise StorageBackendError("boto3 is required for the S3 storage backend") from exc
return boto3.client( return boto3.client(
"s3", "s3",
endpoint_url=self.endpoint_url, endpoint_url=self.endpoint_url,

View File

@@ -2,15 +2,17 @@ from __future__ import annotations
from collections import defaultdict from collections import defaultdict
from pathlib import PurePosixPath from pathlib import PurePosixPath
from typing import Iterable from typing import TYPE_CHECKING, Iterable
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from govoplan_campaign.backend.db.models import CampaignJob
from govoplan_files.backend.db.models import CampaignAttachmentUse, FileAsset, FileBlob, FileVersion from govoplan_files.backend.db.models import CampaignAttachmentUse, FileAsset, FileBlob, FileVersion
from govoplan_files.backend.storage.common import utcnow from govoplan_files.backend.storage.common import utcnow
from govoplan_files.backend.storage.files import current_version_and_blob, list_assets_for_user from govoplan_files.backend.storage.files import current_version_and_blob, list_assets_for_user
if TYPE_CHECKING:
from govoplan_campaign.backend.db.models import CampaignJob
def _candidate_match_keys(raw_match: str) -> set[str]: def _candidate_match_keys(raw_match: str) -> set[str]:
cleaned = raw_match.replace("\\", "/").strip().strip("/") cleaned = raw_match.replace("\\", "/").strip().strip("/")

View File

@@ -10,7 +10,7 @@ from sqlalchemy import or_
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from govoplan_core.db.models import Group, Tenant, User from govoplan_core.db.models import Group, Tenant, User
from govoplan_campaign.backend.db.models import Campaign from govoplan_core.core.optional import reraise_unless_missing_package
from govoplan_files.backend.db.models import CampaignAttachmentUse, FileAsset, FileBlob, FileShare, FileVersion from govoplan_files.backend.db.models import CampaignAttachmentUse, FileAsset, FileBlob, FileShare, FileVersion
from govoplan_files.backend.runtime import settings from govoplan_files.backend.runtime import settings
from govoplan_files.backend.storage.access import ensure_owner_access, user_group_ids from govoplan_files.backend.storage.access import ensure_owner_access, user_group_ids
@@ -19,6 +19,15 @@ from govoplan_files.backend.storage.common import FileConflictResolution, FileSt
from govoplan_files.backend.storage.paths import filename_from_path, join_folder_filename, normalize_folder, normalize_logical_path, safe_storage_component from govoplan_files.backend.storage.paths import filename_from_path, join_folder_filename, normalize_folder, normalize_logical_path, safe_storage_component
def _campaign_model():
try:
from govoplan_campaign.backend.db.models import Campaign
except ModuleNotFoundError as exc:
reraise_unless_missing_package(exc, "govoplan_campaign")
raise FileStorageError("Campaign module is not installed") from exc
return Campaign
def _asset_query_for_owner(session: Session, *, tenant_id: str, owner_type: str, owner_id: str): def _asset_query_for_owner(session: Session, *, tenant_id: str, owner_type: str, owner_id: str):
query = session.query(FileAsset).filter(FileAsset.tenant_id == tenant_id, FileAsset.owner_type == owner_type) query = session.query(FileAsset).filter(FileAsset.tenant_id == tenant_id, FileAsset.owner_type == owner_type)
if owner_type == "user": if owner_type == "user":
@@ -296,6 +305,7 @@ def share_file(
if target_id != tenant_id or not tenant or not tenant.is_active: if target_id != tenant_id or not tenant or not tenant.is_active:
raise FileStorageError("Tenant not found") raise FileStorageError("Tenant not found")
if target_type == "campaign": if target_type == "campaign":
Campaign = _campaign_model()
campaign = session.get(Campaign, target_id) campaign = session.get(Campaign, target_id)
if not campaign or campaign.tenant_id != tenant_id: if not campaign or campaign.tenant_id != tenant_id:
raise FileStorageError("Campaign not found") raise FileStorageError("Campaign not found")
@@ -326,6 +336,79 @@ def share_file(
return share return share
def share_files(
session: Session,
*,
tenant_id: str,
assets: Iterable[FileAsset],
target_type: str,
target_id: str,
permission: str,
user_id: str,
) -> list[FileShare]:
target_type = target_type.lower().strip()
permission = permission.lower().strip()
if target_type not in {"user", "group", "campaign", "tenant"}:
raise FileStorageError("Unsupported share target")
if permission not in {"read", "write", "manage"}:
raise FileStorageError("Unsupported file permission")
if target_type == "user":
target_user = session.get(User, target_id)
if not target_user or target_user.tenant_id != tenant_id or not target_user.is_active:
raise FileStorageError("User not found")
if target_type == "group":
group = session.get(Group, target_id)
if not group or group.tenant_id != tenant_id or not group.is_active:
raise FileStorageError("Group not found")
if target_type == "tenant":
tenant = session.get(Tenant, target_id)
if target_id != tenant_id or not tenant or not tenant.is_active:
raise FileStorageError("Tenant not found")
if target_type == "campaign":
Campaign = _campaign_model()
campaign = session.get(Campaign, target_id)
if not campaign or campaign.tenant_id != tenant_id:
raise FileStorageError("Campaign not found")
asset_list = list(assets)
if not asset_list:
return []
for asset in asset_list:
if asset.tenant_id != tenant_id:
raise FileStorageError("File not found")
existing_by_asset: dict[str, FileShare] = {}
for share in session.query(FileShare).filter(
FileShare.tenant_id == tenant_id,
FileShare.file_asset_id.in_([asset.id for asset in asset_list]),
FileShare.target_type == target_type,
FileShare.target_id == target_id,
FileShare.revoked_at.is_(None),
).all():
existing_by_asset.setdefault(share.file_asset_id, share)
shares: list[FileShare] = []
for asset in asset_list:
existing = existing_by_asset.get(asset.id)
if existing:
existing.permission = permission
session.add(existing)
shares.append(existing)
continue
share = FileShare(
tenant_id=tenant_id,
file_asset_id=asset.id,
target_type=target_type,
target_id=target_id,
permission=permission,
created_by_user_id=user_id,
)
session.add(share)
shares.append(share)
return shares
def soft_delete_assets(session: Session, assets: Iterable[FileAsset]) -> int: def soft_delete_assets(session: Session, assets: Iterable[FileAsset]) -> int:
count = 0 count = 0
now = utcnow() now = utcnow()

View File

@@ -1,6 +1,6 @@
{ {
"name": "@govoplan/files-webui", "name": "@govoplan/files-webui",
"version": "0.1.0", "version": "0.1.2",
"private": true, "private": true,
"type": "module", "type": "module",
"main": "src/index.ts", "main": "src/index.ts",
@@ -21,6 +21,11 @@
"react-dom": "^19.0.0", "react-dom": "^19.0.0",
"react-router-dom": "^7.1.1", "react-router-dom": "^7.1.1",
"lucide-react": "^0.555.0", "lucide-react": "^0.555.0",
"@govoplan/core-webui": "^0.1.0" "@govoplan/core-webui": "^0.1.2"
},
"peerDependenciesMeta": {
"@govoplan/core-webui": {
"optional": true
}
} }
} }

View File

@@ -1,4 +1,4 @@
import { apiFetch, apiUrl, authHeaders, csrfToken, type ApiSettings } from "@govoplan/core-webui"; import { ApiError, apiFetch, apiUrl, authHeaders, csrfToken, type ApiSettings } from "@govoplan/core-webui";
export type FileSpace = { export type FileSpace = {
id: string; id: string;
@@ -40,6 +40,7 @@ export type ManagedFile = {
export type FileListResponse = { files: ManagedFile[] }; export type FileListResponse = { files: ManagedFile[] };
export type FileSpacesResponse = { spaces: FileSpace[] }; export type FileSpacesResponse = { spaces: FileSpace[] };
export type FileUploadResponse = { files: ManagedFile[] }; export type FileUploadResponse = { files: ManagedFile[] };
export type FileUploadProgress = { loaded: number; total?: number; percentage: number | null };
export type FileFolder = { export type FileFolder = {
id: string; id: string;
tenant_id: string; tenant_id: string;
@@ -102,7 +103,16 @@ export function listFiles(settings: ApiSettings, params: { owner_type?: string;
export async function uploadFiles( export async function uploadFiles(
settings: ApiSettings, settings: ApiSettings,
files: File[], files: File[],
options: { owner_type: "user" | "group"; owner_id: string; path?: string; campaign_id?: string; unpack_zip?: boolean; conflict_strategy?: ConflictStrategy; conflict_resolutions?: ConflictResolution[] } options: {
owner_type: "user" | "group";
owner_id: string;
path?: string;
campaign_id?: string;
unpack_zip?: boolean;
conflict_strategy?: ConflictStrategy;
conflict_resolutions?: ConflictResolution[];
onProgress?: (progress: FileUploadProgress) => void;
}
): Promise<FileUploadResponse> { ): Promise<FileUploadResponse> {
const form = new FormData(); const form = new FormData();
files.forEach((file) => form.append("files", file)); files.forEach((file) => form.append("files", file));
@@ -113,9 +123,54 @@ export async function uploadFiles(
if (options.unpack_zip) form.append("unpack_zip", "true"); if (options.unpack_zip) form.append("unpack_zip", "true");
if (options.conflict_strategy) form.append("conflict_strategy", options.conflict_strategy); if (options.conflict_strategy) form.append("conflict_strategy", options.conflict_strategy);
if (options.conflict_resolutions?.length) form.append("conflict_resolutions_json", JSON.stringify(options.conflict_resolutions)); if (options.conflict_resolutions?.length) form.append("conflict_resolutions_json", JSON.stringify(options.conflict_resolutions));
if (options.onProgress) return uploadFilesWithProgress(settings, form, options.onProgress);
return apiFetch<FileUploadResponse>(settings, "/api/v1/files/upload", { method: "POST", body: form }); return apiFetch<FileUploadResponse>(settings, "/api/v1/files/upload", { method: "POST", body: form });
} }
function uploadFilesWithProgress(
settings: ApiSettings,
form: FormData,
onProgress: (progress: FileUploadProgress) => void
): Promise<FileUploadResponse> {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("POST", apiUrl(settings, "/api/v1/files/upload"));
xhr.withCredentials = true;
for (const [key, value] of authHeaders(settings)) xhr.setRequestHeader(key, value);
const csrf = csrfToken();
if (csrf) xhr.setRequestHeader("X-CSRF-Token", csrf);
xhr.upload.onprogress = (event) => {
const total = event.lengthComputable ? event.total : undefined;
onProgress({
loaded: event.loaded,
total,
percentage: total && total > 0 ? Math.round((event.loaded / total) * 100) : null
});
};
xhr.onerror = () => reject(new Error("Upload failed because the network request could not be completed."));
xhr.onabort = () => reject(new Error("Upload was cancelled."));
xhr.onload = () => {
const responseText = xhr.responseText || "";
if (xhr.status < 200 || xhr.status >= 300) {
reject(new ApiError(xhr.status, xhr.statusText, responseText));
return;
}
onProgress({ loaded: 1, total: 1, percentage: 100 });
if (xhr.status === 204 || !responseText) {
resolve({ files: [] });
return;
}
const contentType = xhr.getResponseHeader("content-type") || "";
resolve(contentType.includes("application/json") ? JSON.parse(responseText) as FileUploadResponse : { files: [] });
};
onProgress({ loaded: 0, total: undefined, percentage: 0 });
xhr.send(form);
});
}
export function deleteFile(settings: ApiSettings, fileId: string): Promise<BulkDeleteResponse> { export function deleteFile(settings: ApiSettings, fileId: string): Promise<BulkDeleteResponse> {
return apiFetch<BulkDeleteResponse>(settings, `/api/v1/files/${fileId}`, { method: "DELETE" }); return apiFetch<BulkDeleteResponse>(settings, `/api/v1/files/${fileId}`, { method: "DELETE" });
} }
@@ -124,13 +179,22 @@ export function bulkDeleteFiles(settings: ApiSettings, fileIds: string[]): Promi
return apiFetch<BulkDeleteResponse>(settings, "/api/v1/files/bulk-delete", { method: "POST", body: JSON.stringify({ file_ids: fileIds }) }); return apiFetch<BulkDeleteResponse>(settings, "/api/v1/files/bulk-delete", { method: "POST", body: JSON.stringify({ file_ids: fileIds }) });
} }
export function shareFileWithCampaign(settings: ApiSettings, fileId: string, campaignId: string): Promise<FileShare> { export type FileBulkShareResponse = { shares: FileShare[]; shared_count: number };
return apiFetch<FileShare>(settings, `/api/v1/files/${fileId}/shares`, {
export function shareFilesWithCampaign(settings: ApiSettings, fileIds: string[], campaignId: string): Promise<FileBulkShareResponse> {
return apiFetch<FileBulkShareResponse>(settings, "/api/v1/files/bulk-shares", {
method: "POST", method: "POST",
body: JSON.stringify({ target_type: "campaign", target_id: campaignId, permission: "read" }) body: JSON.stringify({ file_ids: fileIds, target_type: "campaign", target_id: campaignId, permission: "read" })
}); });
} }
export async function shareFileWithCampaign(settings: ApiSettings, fileId: string, campaignId: string): Promise<FileShare> {
const response = await shareFilesWithCampaign(settings, [fileId], campaignId);
const share = response.shares[0];
if (!share) throw new Error("File share was not created.");
return share;
}
export function bulkRenameFiles( export function bulkRenameFiles(
settings: ApiSettings, settings: ApiSettings,
payload: { file_ids: string[]; folder_paths?: string[]; owner_type?: "user" | "group"; owner_id?: string; mode: "direct" | "prefix" | "suffix" | "replace"; new_name?: string; find?: string; replacement?: string; prefix?: string; suffix?: string; recursive?: boolean; dry_run?: boolean } payload: { file_ids: string[]; folder_paths?: string[]; owner_type?: "user" | "group"; owner_id?: string; mode: "direct" | "prefix" | "suffix" | "replace"; new_name?: string; find?: string; replacement?: string; prefix?: string; suffix?: string; recursive?: boolean; dry_run?: boolean }

View File

@@ -1,10 +1,11 @@
import { useEffect, useMemo, useRef, useState, type DragEvent as ReactDragEvent, type KeyboardEvent as ReactKeyboardEvent, type MouseEvent as ReactMouseEvent } from "react"; import { useEffect, useMemo, useState, type DragEvent as ReactDragEvent, type KeyboardEvent as ReactKeyboardEvent, type MouseEvent as ReactMouseEvent } from "react";
import { ChevronRight, Copy, Download, File, Folder, Home, MoveRight, Plus, Search, Trash2, UploadCloud } from "lucide-react"; import { ChevronRight, Copy, Download, File, Folder, Home, Link2, MoveRight, Plus, Search, Trash2, UploadCloud } from "lucide-react";
import { import {
Button, Button,
ConfirmDialog, ConfirmDialog,
DismissibleAlert, DismissibleAlert,
FieldLabel, FieldLabel,
FileDropZone,
FormField, FormField,
LoadingIndicator, LoadingIndicator,
ToggleSwitch, ToggleSwitch,
@@ -75,6 +76,8 @@ import { useFileTreeState } from "./hooks/useFileTreeState";
import { useFileDialogs } from "./hooks/useFileDialogs"; import { useFileDialogs } from "./hooks/useFileDialogs";
import { useFileDragDropState } from "./hooks/useFileDragDropState"; import { useFileDragDropState } from "./hooks/useFileDragDropState";
type UploadPhase = "idle" | "uploading" | "unpacking" | "finalizing";
export default function FilesPage({ settings, auth }: { settings: ApiSettings; auth: AuthInfo }) { export default function FilesPage({ settings, auth }: { settings: ApiSettings; auth: AuthInfo }) {
const canDownload = hasScope(auth, "files:download"); const canDownload = hasScope(auth, "files:download");
const canUpload = hasScope(auth, "files:upload"); const canUpload = hasScope(auth, "files:upload");
@@ -98,9 +101,12 @@ export default function FilesPage({ settings, auth }: { settings: ApiSettings; a
const [unmatchedCount, setUnmatchedCount] = useState<number | null>(null); const [unmatchedCount, setUnmatchedCount] = useState<number | null>(null);
const [unpackZip, setUnpackZip] = useState(false); const [unpackZip, setUnpackZip] = useState(false);
const [busy, setBusy] = useState(false); const [busy, setBusy] = useState(false);
const [uploadActive, setUploadActive] = useState(false);
const [uploadPhase, setUploadPhase] = useState<UploadPhase>("idle");
const [uploadProgress, setUploadProgress] = useState<number | null>(null);
const [message, setMessage] = useState(""); const [message, setMessage] = useState("");
const [error, setError] = useState(""); const [error, setError] = useState("");
const { dragActive, setDragActive, internalDrag, setInternalDrag, dropTargetKey, setDropTargetKey, clearDropState: clearDragDropState } = useFileDragDropState(); const { setDragActive, internalDrag, setInternalDrag, dropTargetKey, setDropTargetKey, clearDropState: clearDragDropState } = useFileDragDropState();
const { const {
dialog, dialog,
setDialog, setDialog,
@@ -130,8 +136,6 @@ export default function FilesPage({ settings, auth }: { settings: ApiSettings; a
const [renameSuffix, setRenameSuffix] = useState(""); const [renameSuffix, setRenameSuffix] = useState("");
const [renameRecursive, setRenameRecursive] = useState(false); const [renameRecursive, setRenameRecursive] = useState(false);
const [renamePreview, setRenamePreview] = useState<RenameResponse | null>(null); const [renamePreview, setRenamePreview] = useState<RenameResponse | null>(null);
const fileInputRef = useRef<HTMLInputElement | null>(null);
const visibleFiles = searchActive && searchResults ? searchResults : files; const visibleFiles = searchActive && searchResults ? searchResults : files;
const explorerEntries = useMemo(() => { const explorerEntries = useMemo(() => {
const entries = buildExplorerEntries(visibleFiles, folders, currentFolder, searchActive); const entries = buildExplorerEntries(visibleFiles, folders, currentFolder, searchActive);
@@ -275,6 +279,9 @@ export default function FilesPage({ settings, auth }: { settings: ApiSettings; a
function closeDialog() { function closeDialog() {
closeRawDialog(); closeRawDialog();
setNewFolderError(""); setNewFolderError("");
setUploadActive(false);
setUploadPhase("idle");
setUploadProgress(null);
} }
function updateActiveDialogFolder(spaceId: string, folderPath: string) { function updateActiveDialogFolder(spaceId: string, folderPath: string) {
@@ -309,7 +316,11 @@ export default function FilesPage({ settings, auth }: { settings: ApiSettings; a
return; return;
} }
} }
const uploadsZipArchive = unpackZip && selected.some((file) => file.name.toLowerCase().endsWith(".zip"));
setBusy(true); setBusy(true);
setUploadActive(true);
setUploadPhase("uploading");
setUploadProgress(0);
setError(""); setError("");
setMessage(`Uploading ${selected.length} file(s)…`); setMessage(`Uploading ${selected.length} file(s)…`);
try { try {
@@ -319,8 +330,17 @@ export default function FilesPage({ settings, auth }: { settings: ApiSettings; a
path: target.folderPath, path: target.folderPath,
unpack_zip: unpackZip, unpack_zip: unpackZip,
conflict_strategy: options.conflictStrategy ?? "reject", conflict_strategy: options.conflictStrategy ?? "reject",
conflict_resolutions: options.conflictResolutions conflict_resolutions: options.conflictResolutions,
onProgress: ({ percentage }) => {
setUploadProgress(percentage);
if (percentage !== null && percentage >= 100) {
setUploadPhase(uploadsZipArchive ? "unpacking" : "finalizing");
setMessage(uploadsZipArchive ? "Unpacking ZIP upload…" : "Finalizing upload…");
}
}
}); });
setUploadPhase("finalizing");
setUploadProgress(100);
setMessage(`Uploaded ${response.files.length} file(s) into ${target.folderPath || "Root"}.`); setMessage(`Uploaded ${response.files.length} file(s) into ${target.folderPath || "Root"}.`);
closeDialog(); closeDialog();
setConflictDialog(null); setConflictDialog(null);
@@ -331,7 +351,9 @@ export default function FilesPage({ settings, auth }: { settings: ApiSettings; a
setMessage(""); setMessage("");
} finally { } finally {
setBusy(false); setBusy(false);
if (fileInputRef.current) fileInputRef.current.value = ""; setUploadActive(false);
setUploadPhase("idle");
setUploadProgress(null);
} }
} }
@@ -386,25 +408,29 @@ export default function FilesPage({ settings, auth }: { settings: ApiSettings; a
} }
} }
async function runPatternSearch() { async function runPatternSearch(patternOverride = searchPattern, caseSensitiveOverride = searchCaseSensitive) {
if (!activeSpace || !searchPattern.trim()) { const trimmedPattern = patternOverride.trim();
if (!activeSpace || !trimmedPattern) {
await clearSearch(); await clearSearch();
return; return;
} }
const caseSensitive = caseSensitiveOverride;
setBusy(true); setBusy(true);
setError(""); setError("");
setMessage(""); setMessage("");
try { try {
const response = await resolveFilePatterns(settings, { const response = await resolveFilePatterns(settings, {
patterns: [searchPattern.trim()], patterns: [trimmedPattern],
owner_type: activeSpace.owner_type, owner_type: activeSpace.owner_type,
owner_id: activeSpace.owner_id, owner_id: activeSpace.owner_id,
path_prefix: currentFolder, path_prefix: currentFolder,
include_unmatched: true, include_unmatched: true,
case_sensitive: searchCaseSensitive case_sensitive: caseSensitive
}); });
setSearchResults(response.patterns.flatMap((pattern) => pattern.matches)); setSearchResults(response.patterns.flatMap((pattern) => pattern.matches));
setSearchActive(true); setSearchActive(true);
setSearchPattern(trimmedPattern);
setSearchCaseSensitive(caseSensitive);
setUnmatchedCount(response.unmatched.length); setUnmatchedCount(response.unmatched.length);
setSelectedFileIds(new Set()); setSelectedFileIds(new Set());
setSelectedFolderPaths(new Set()); setSelectedFolderPaths(new Set());
@@ -1127,6 +1153,14 @@ export default function FilesPage({ settings, auth }: { settings: ApiSettings; a
</div> </div>
); );
const uploadBusyLabel = uploadPhase === "unpacking" ? "Unpacking ZIP archive" : "Uploading files";
const uploadProgressLabel = uploadPhase === "unpacking"
? "Extracting files on the server…"
: uploadProgress !== null && uploadProgress >= 100
? "Finalizing upload…"
: undefined;
const visibleUploadProgress = uploadPhase === "unpacking" ? null : uploadProgress;
return ( return (
<div className="workspace-data-page module-entry-page file-manager-page file-manager-fullscreen"> <div className="workspace-data-page module-entry-page file-manager-page file-manager-fullscreen">
{error && ( {error && (
@@ -1199,13 +1233,15 @@ export default function FilesPage({ settings, auth }: { settings: ApiSettings; a
</span> </span>
))} ))}
</nav> </nav>
<div className="file-search-row"> <FileSearchRow
<Search size={17} aria-hidden="true" /> value={searchPattern}
<input value={searchPattern} placeholder="Search this folder: *.pdf, **/*.pdf or 2026-??-*.pdf" onChange={(event) => setSearchPattern(event.target.value)} onKeyDown={(event) => { if (event.key === "Enter") void runPatternSearch(); }} /> caseSensitive={searchCaseSensitive}
<ToggleSwitch label="Case sensitive" checked={searchCaseSensitive} onChange={setSearchCaseSensitive} disabled={busy} /> busy={busy}
<Button onClick={() => void runPatternSearch()} disabled={busy || !activeSpace}>Search</Button> searchActive={searchActive}
{searchActive && <Button onClick={() => void clearSearch()} disabled={busy}>Clear</Button>} disabled={!activeSpace}
</div> onSearch={(patternValue, caseSensitiveValue) => void runPatternSearch(patternValue, caseSensitiveValue)}
onClear={() => void clearSearch()}
/>
<div className="file-list-meta"> <div className="file-list-meta">
<span>{selectedSummary}</span> <span>{selectedSummary}</span>
<span>{explorerEntries.filter((entry) => entry.kind === "folder").length} folder(s) · {explorerEntries.filter((entry) => entry.kind === "file").length} file(s)</span> <span>{explorerEntries.filter((entry) => entry.kind === "folder").length} folder(s) · {explorerEntries.filter((entry) => entry.kind === "file").length} file(s)</span>
@@ -1313,7 +1349,16 @@ export default function FilesPage({ settings, auth }: { settings: ApiSettings; a
<div className="file-list-name-cell"> <div className="file-list-name-cell">
<div className="file-list-name"> <div className="file-list-name">
<File className="file-row-icon" size={20} aria-hidden="true" /> <File className="file-row-icon" size={20} aria-hidden="true" />
<span><strong>{searchActive ? entry.file.display_path : entry.file.filename}</strong></span> <span>
<strong>{searchActive ? entry.file.display_path : entry.file.filename}</strong>
<small
className={`file-linkage-status ${activeCampaignShareCount(entry.file) > 0 ? "is-linked" : ""}`}
title={campaignShareTitle(entry.file)}
>
{activeCampaignShareCount(entry.file) > 0 && <Link2 size={12} aria-hidden="true" />}
{campaignShareLabel(entry.file)}
</small>
</span>
</div> </div>
</div> </div>
<span>{formatBytes(entry.file.size_bytes)}</span> <span>{formatBytes(entry.file.size_bytes)}</span>
@@ -1378,34 +1423,15 @@ export default function FilesPage({ settings, auth }: { settings: ApiSettings; a
{dialog === "upload" && ( {dialog === "upload" && (
<FileDialog title={`Upload to ${activeDialogSpace?.label || "Files"} / ${activeDialogTarget?.folderPath || "Root"}`} onClose={closeDialog}> <FileDialog title={`Upload to ${activeDialogSpace?.label || "Files"} / ${activeDialogTarget?.folderPath || "Root"}`} onClose={closeDialog}>
<div <FileDropZone
className={`file-upload-drop-zone ${dragActive ? "is-active" : ""}`} disabled={busy || !activeDialogSpace || !canUpload}
role="button" busy={uploadActive}
tabIndex={busy || !activeDialogSpace || !canUpload ? -1 : 0} progress={visibleUploadProgress}
aria-label="Drop files here or click to select files" busyLabel={uploadBusyLabel}
aria-disabled={busy || !activeDialogSpace || !canUpload} progressLabel={uploadProgressLabel}
onClick={() => { note={`Files are uploaded into ${activeDialogTarget?.folderPath || "Root"}.`}
if (!busy && activeDialogSpace && canUpload) fileInputRef.current?.click(); onFiles={(files) => handleFilesUpload(files)}
}} />
onKeyDown={(event) => {
if ((event.key === "Enter" || event.key === " ") && !busy && activeDialogSpace && canUpload) {
event.preventDefault();
fileInputRef.current?.click();
}
}}
onDragOver={(event) => { event.preventDefault(); setDragActive(true); }}
onDragLeave={() => setDragActive(false)}
onDrop={(event) => {
event.preventDefault();
setDragActive(false);
void handleFilesUpload(event.dataTransfer.files);
}}
>
<UploadCloud size={28} aria-hidden="true" />
<strong>Drop files here</strong>
<span>or click to select files</span>
<span className="muted small-text">Files are uploaded into {activeDialogTarget?.folderPath || "Root"}.</span>
</div>
<ToggleSwitch label="Unpack ZIP uploads" checked={unpackZip} onChange={setUnpackZip} disabled={busy} /> <ToggleSwitch label="Unpack ZIP uploads" checked={unpackZip} onChange={setUnpackZip} disabled={busy} />
<div className="field-block"> <div className="field-block">
<FieldLabel className="form-label" help="Choose the destination folder before selecting or dropping files.">Destination folder</FieldLabel> <FieldLabel className="form-label" help="Choose the destination folder before selecting or dropping files.">Destination folder</FieldLabel>
@@ -1417,10 +1443,8 @@ export default function FilesPage({ settings, auth }: { settings: ApiSettings; a
onSelect={(folderPath) => activeDialogTarget && updateActiveDialogFolder(activeDialogTarget.spaceId, folderPath)} onSelect={(folderPath) => activeDialogTarget && updateActiveDialogFolder(activeDialogTarget.spaceId, folderPath)}
/> />
</div> </div>
<input ref={fileInputRef} type="file" multiple hidden onChange={(event) => event.target.files && void handleFilesUpload(event.target.files)} />
<div className="button-row compact-actions align-end"> <div className="button-row compact-actions align-end">
<Button onClick={closeDialog} disabled={busy}>Cancel</Button> <Button onClick={closeDialog} disabled={busy}>Cancel</Button>
<Button variant="primary" onClick={() => fileInputRef.current?.click()} disabled={busy || !activeDialogSpace || !canUpload}>Select files</Button>
</div> </div>
</FileDialog> </FileDialog>
)} )}
@@ -1527,3 +1551,72 @@ export default function FilesPage({ settings, auth }: { settings: ApiSettings; a
); );
} }
function FileSearchRow({
value,
caseSensitive,
busy,
searchActive,
disabled,
onSearch,
onClear
}: {
value: string;
caseSensitive: boolean;
busy: boolean;
searchActive: boolean;
disabled: boolean;
onSearch: (value: string, caseSensitive: boolean) => void;
onClear: () => void;
}) {
const [draft, setDraft] = useState(value);
const [caseSensitiveDraft, setCaseSensitiveDraft] = useState(caseSensitive);
useEffect(() => {
setDraft(value);
}, [value]);
useEffect(() => {
setCaseSensitiveDraft(caseSensitive);
}, [caseSensitive]);
function clear() {
setDraft("");
onClear();
}
return (
<div className="file-search-row">
<Search size={17} aria-hidden="true" />
<input
value={draft}
placeholder="Search this folder: *.pdf, **/*.pdf or 2026-??-*.pdf"
onChange={(event) => setDraft(event.target.value)}
onKeyDown={(event) => { if (event.key === "Enter") onSearch(draft, caseSensitiveDraft); }}
/>
<ToggleSwitch label="Case sensitive" checked={caseSensitiveDraft} onChange={setCaseSensitiveDraft} disabled={busy || disabled} />
<Button onClick={() => onSearch(draft, caseSensitiveDraft)} disabled={busy || disabled}>Search</Button>
{searchActive && <Button onClick={clear} disabled={busy}>Clear</Button>}
</div>
);
}
function activeCampaignShares(file: ManagedFile) {
return (file.shares ?? []).filter((share) => share.target_type === "campaign" && !share.revoked_at);
}
function activeCampaignShareCount(file: ManagedFile): number {
return activeCampaignShares(file).length;
}
function campaignShareLabel(file: ManagedFile): string {
const count = activeCampaignShareCount(file);
if (count === 0) return "No campaign links";
if (count === 1) return "Linked to 1 campaign";
return `Linked to ${count} campaigns`;
}
function campaignShareTitle(file: ManagedFile): string | undefined {
const shares = activeCampaignShares(file);
if (shares.length === 0) return undefined;
return shares.map((share) => share.target_id).join(", ");
}

View File

@@ -1,5 +1,7 @@
import { createElement, lazy } from "react"; import { createElement, lazy } from "react";
import type { PlatformWebModule } from "@govoplan/core-webui"; import type { FilesFileExplorerUiCapability, PlatformWebModule } from "@govoplan/core-webui";
import { FolderTree } from "./features/files/components/FileManagerComponents";
const FilesPage = lazy(() => import("./features/files/FilesPage")); const FilesPage = lazy(() => import("./features/files/FilesPage"));
const fileRead = ["files:file:read"]; const fileRead = ["files:file:read"];
@@ -12,7 +14,10 @@ export const filesModule: PlatformWebModule = {
navItems: [{ to: "/files", label: "Files", iconName: "folder", anyOf: fileRead, order: 40 }], navItems: [{ to: "/files", label: "Files", iconName: "folder", anyOf: fileRead, order: 40 }],
routes: [ routes: [
{ path: "/files", anyOf: fileRead, order: 40, render: ({ settings, auth }) => createElement(FilesPage, { settings, auth }) } { path: "/files", anyOf: fileRead, order: 40, render: ({ settings, auth }) => createElement(FilesPage, { settings, auth }) }
] ],
uiCapabilities: {
"files.fileExplorer": { FolderTree } satisfies FilesFileExplorerUiCapability
}
}; };
export default filesModule; export default filesModule;

View File

@@ -356,6 +356,16 @@
font-size: 12px; font-size: 12px;
} }
.file-linkage-status {
display: inline-flex;
align-items: center;
gap: 4px;
}
.file-linkage-status.is-linked {
color: var(--text-strong);
}
.file-row-icon { .file-row-icon {
color: var(--muted); color: var(--muted);
flex: 0 0 auto; flex: 0 0 auto;
@@ -473,37 +483,6 @@
padding: 18px; padding: 18px;
} }
.file-upload-drop-zone {
display: grid;
place-items: center;
gap: 8px;
min-height: 170px;
border: 1px dashed var(--line-dark);
border-radius: 14px;
background: var(--panel-soft);
color: var(--muted);
text-align: center;
cursor: pointer;
transition: border-color .16s ease, background .16s ease, box-shadow .16s ease;
}
.file-upload-drop-zone:hover,
.file-upload-drop-zone:focus-visible,
.file-upload-drop-zone.is-active {
border-color: #0d6efd;
background: rgba(13, 110, 253, .08);
}
.file-upload-drop-zone:focus-visible {
outline: none;
box-shadow: 0 0 0 3px rgba(13, 110, 253, .18);
}
.file-upload-drop-zone[aria-disabled="true"] {
cursor: not-allowed;
opacity: .65;
}
.field-error { .field-error {
color: var(--danger-text); color: var(--danger-text);
font-weight: 700; font-weight: 700;