6 Commits

Author SHA1 Message Date
18e6c3eb9b Release v0.1.6 2026-07-07 15:55:37 +02:00
a5c24fe73e Release v0.1.5 2026-07-07 15:49:06 +02:00
ee5b06b1e7 Release v0.1.4 2026-07-02 14:59:52 +02:00
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
32 changed files with 2698 additions and 294 deletions

View File

@@ -0,0 +1,35 @@
---
name: "Bug"
about: "Report a reproducible defect, regression, or incorrect behavior"
title: "[Bug] "
labels:
- type/bug
- status/triage
- module/files
---
## Scope
- Repository:
- Area/module:
- Affected version or commit:
## Behavior
Expected:
Actual:
## Reproduction
1.
2.
3.
## Evidence
Logs, screenshots, traces, or failing test output:
## Verification Target
Command or workflow that should pass when fixed:

View File

@@ -0,0 +1 @@
blank_issues_enabled: false

View File

@@ -0,0 +1,27 @@
---
name: "Docs / workflow"
about: "Request documentation, process, or developer workflow changes"
title: "[Docs] "
labels:
- type/docs
- status/triage
- module/files
- area/docs
---
## Scope
- Repository:
- Document or workflow:
## Current State
What is missing, unclear, duplicated, or stale?
## Desired State
What should the docs or workflow make clear?
## Verification Target
How should this be checked?

View File

@@ -0,0 +1,32 @@
---
name: "Feature"
about: "Propose new user-visible behavior or platform capability"
title: "[Feature] "
labels:
- type/feature
- status/triage
- module/files
---
## Problem
What user, operator, or developer problem should this solve?
## Proposed Capability
What should exist when this is done?
## Ownership
- Owning repository:
- Related module repositories:
- Extension point or integration boundary:
## Acceptance Criteria
- [ ]
- [ ]
## Verification Target
Command, scenario, or UI flow that should prove completion:

View File

@@ -0,0 +1,28 @@
---
name: "Task"
about: "Track implementation, maintenance, or migration work"
title: "[Task] "
labels:
- type/task
- status/triage
- module/files
---
## Objective
What needs to be completed?
## Scope
- Owning repository:
- In-scope:
- Out-of-scope:
## Checklist
- [ ]
- [ ]
## Verification Target
Command or manual check:

View File

@@ -0,0 +1,25 @@
---
name: "Tech debt"
about: "Track cleanup, refactoring, risk reduction, or deferred engineering work"
title: "[Debt] "
labels:
- type/debt
- status/triage
- module/files
---
## Current Cost
What does this make harder, riskier, slower, or more fragile?
## Desired Shape
What should the code, tests, or architecture look like afterwards?
## Constraints
What behavior, compatibility, or module boundary must be preserved?
## Verification Target
Focused checks that should pass:

View File

@@ -0,0 +1,15 @@
## Issue
Closes #
## Summary
-
## Verification
-
## Notes
Follow-up issues:

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

@@ -46,7 +46,10 @@ Frontend package:
@govoplan/files-webui
```
The campaign module can integrate with files when both modules are installed, for example for managed attachment selection and campaign file sharing.
The campaign module can integrate with files when both modules are installed,
for example for managed attachment selection and campaign file sharing. Files
does not import campaign internals; campaign share/existence checks use the core
`campaigns.access` capability registered by the campaign module.
Platform RBAC and governance rules are documented in `govoplan-core/docs/`.

View File

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

View File

@@ -4,14 +4,14 @@ build-backend = "setuptools.build_meta"
[project]
name = "govoplan-files"
version = "0.1.0"
version = "0.1.6"
description = "GovOPlaN files module with backend and WebUI integration."
readme = "README.md"
requires-python = ">=3.12"
license = { file = "LICENSE" }
authors = [{ name = "GovOPlaN" }]
dependencies = [
"govoplan-core>=0.1.0",
"govoplan-core>=0.1.6",
]
[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(registry=context.registry, settings=context.settings)
return FilesCampaignCapability()

View File

@@ -2,6 +2,7 @@ from __future__ import annotations
from pathlib import Path
from govoplan_core.core.module_guards import drop_table_retirement_provider, persistent_table_uninstall_guard
from govoplan_core.core.modules import FrontendModule, MigrationSpec, ModuleContext, ModuleManifest, NavItem, PermissionDefinition, RoleTemplate
from govoplan_core.db.base import Base
from govoplan_files.backend.db import models as file_models # noqa: F401 - populate Files ORM metadata
@@ -54,10 +55,30 @@ ROLE_TEMPLATES = (
)
def _tenant_summary(session, tenant_id: str) -> dict[str, int]:
from govoplan_files.backend.db.models import FileAsset
return {"files": session.query(FileAsset).filter(FileAsset.tenant_id == tenant_id).count()}
def _veto_group_delete(session, tenant_id: str, group_id: str) -> None:
from govoplan_files.backend.db.models import FileAsset, FileFolder, FileShare
owned_asset_count = session.query(FileAsset).filter(FileAsset.tenant_id == tenant_id, FileAsset.owner_group_id == group_id).count()
owned_folder_count = session.query(FileFolder).filter(FileFolder.tenant_id == tenant_id, FileFolder.owner_group_id == group_id).count()
shared_asset_count = session.query(FileShare).filter(
FileShare.tenant_id == tenant_id,
FileShare.target_type == "group",
FileShare.target_id == group_id,
).count()
if owned_asset_count or owned_folder_count or shared_asset_count:
raise ValueError("Cannot remove the group while it owns files, folders or file shares.")
def _files_router(context: ModuleContext):
from govoplan_files.backend.runtime import configure_runtime
configure_runtime(settings=context.settings)
configure_runtime(registry=context.registry, settings=context.settings)
from govoplan_files.backend.router import router
return router
@@ -66,12 +87,14 @@ def _files_router(context: ModuleContext):
manifest = ModuleManifest(
id="files",
name="Files",
version="1.0.0",
version="0.1.6",
dependencies=("access",),
optional_dependencies=(),
permissions=PERMISSIONS,
route_factory=_files_router,
role_templates=ROLE_TEMPLATES,
tenant_summary_providers=(_tenant_summary,),
delete_veto_providers={"group": (_veto_group_delete,)},
nav_items=(NavItem(path="/files", label="Files", icon="folder", required_any=("files:file:read",), order=40),),
frontend=FrontendModule(
module_id="files",
@@ -82,10 +105,34 @@ manifest = ModuleManifest(
module_id="files",
metadata=Base.metadata,
script_location=str(Path(__file__).with_name("migrations") / "versions"),
retirement_supported=True,
retirement_provider=drop_table_retirement_provider(
file_models.FileBlob,
file_models.FileFolder,
file_models.FileAsset,
file_models.FileVersion,
file_models.FileShare,
file_models.CampaignAttachmentUse,
label="Files",
),
retirement_notes="Destructive retirement drops files-owned database tables after the installer captures a database snapshot.",
),
uninstall_guard_providers=(
persistent_table_uninstall_guard(
file_models.FileBlob,
file_models.FileFolder,
file_models.FileAsset,
file_models.FileVersion,
file_models.FileShare,
file_models.CampaignAttachmentUse,
label="Files",
),
),
capability_factories={
"files.campaign_attachments": lambda context: __import__("govoplan_files.backend.capabilities", fromlist=["campaign_capability"]).campaign_capability(context),
},
)
def get_manifest() -> ModuleManifest:
return manifest

View File

@@ -9,12 +9,14 @@ from urllib.parse import quote
from fastapi import APIRouter, Depends, File as FastAPIFile, Form, HTTPException, UploadFile, status
from fastapi.responses import FileResponse, StreamingResponse
from starlette.background import BackgroundTask
from sqlalchemy import or_
from sqlalchemy.orm import Session
from govoplan_core.auth.dependencies import ApiPrincipal, has_scope, require_scope
from govoplan_access.backend.auth.dependencies import ApiPrincipal, has_scope, require_scope
from govoplan_core.core.campaigns import CAPABILITY_CAMPAIGNS_ACCESS, CampaignAccessProvider
from govoplan_files.backend.schemas import (
ArchiveRequest,
BulkFileShareRequest,
BulkFileShareResponse,
BulkDeleteRequest,
BulkDeleteResponse,
ConflictResolutionRequest,
@@ -40,13 +42,11 @@ from govoplan_files.backend.schemas import (
TransferResponse,
_conflict_resolutions,
)
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 CampaignAttachmentUse, FileAsset, FileBlob, FileFolder, FileShare, FileVersion
from govoplan_core.db.session import get_session
from govoplan_files.backend.runtime import settings
from govoplan_files.backend.runtime import get_registry, settings
from govoplan_files.backend.storage.paths import UnsafeFilePathError, filename_from_path, normalize_logical_path
from govoplan_files.backend.storage.access import ensure_group_access, user_group_ids
from govoplan_files.backend.storage.access import ensure_group_access, group_refs_for_ids, user_group_ids
from govoplan_files.backend.storage.archives import create_zip_file, extract_zip_upload
from govoplan_files.backend.storage.common import FileStorageError
from govoplan_files.backend.storage.files import (
@@ -57,6 +57,7 @@ from govoplan_files.backend.storage.files import (
list_assets_for_user,
read_asset_bytes,
share_file,
share_files,
soft_delete_assets,
)
from govoplan_files.backend.storage.folders import create_folder, list_folders_for_user, soft_delete_folder
@@ -66,6 +67,15 @@ from govoplan_files.backend.storage.transfers import rename_selection, transfer_
router = APIRouter(prefix="/files", tags=["files"])
def _campaign_access_provider() -> CampaignAccessProvider:
registry = get_registry()
if registry is None or not hasattr(registry, "has_capability") or not registry.has_capability(CAPABILITY_CAMPAIGNS_ACCESS):
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Campaign module is not installed")
capability = registry.require_capability(CAPABILITY_CAMPAIGNS_ACCESS)
if not isinstance(capability, CampaignAccessProvider):
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Campaign access capability is invalid")
return capability
def _is_admin(principal: ApiPrincipal) -> bool:
return has_scope(principal, "files:file:admin")
@@ -105,36 +115,20 @@ def _ensure_campaign_file_access(session: Session, principal: ApiPrincipal, camp
return
if not has_scope(principal, "campaigns:campaign:read"):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Missing scope: campaign:read")
campaign = session.get(Campaign, campaign_id)
if not campaign or campaign.tenant_id != principal.tenant_id:
provider = _campaign_access_provider()
if not provider.campaign_exists(session, tenant_id=principal.tenant_id, campaign_id=campaign_id):
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Campaign not found")
if has_scope(principal, "tenant:*"):
group_ids = set(user_group_ids(session, tenant_id=principal.tenant_id, user_id=principal.user.id))
if provider.can_read_campaign(
session,
tenant_id=principal.tenant_id,
campaign_id=campaign_id,
user_id=principal.user.id,
group_ids=group_ids,
tenant_admin=has_scope(principal, "tenant:*"),
):
return
if campaign.owner_user_id == principal.user.id:
return
group_ids = {
row[0]
for row in session.query(UserGroupMembership.group_id)
.filter(UserGroupMembership.tenant_id == principal.tenant_id, UserGroupMembership.user_id == principal.user.id)
.all()
}
if campaign.owner_group_id and campaign.owner_group_id in group_ids:
return
share = (
session.query(CampaignShare)
.filter(
CampaignShare.tenant_id == principal.tenant_id,
CampaignShare.campaign_id == campaign.id,
CampaignShare.revoked_at.is_(None),
or_(
(CampaignShare.target_type == "user") & (CampaignShare.target_id == principal.user.id),
(CampaignShare.target_type == "group") & (CampaignShare.target_id.in_(group_ids)),
),
)
.first()
)
if share is None:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="No access to this campaign")
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="No access to this campaign")
def _http_error(exc: Exception, *, not_found: bool = False) -> HTTPException:
@@ -183,6 +177,92 @@ def _asset_response(session: Session, asset: FileAsset, *, include_shares: bool
)
def _asset_list_response(session: Session, assets: list[FileAsset], *, include_shares: bool = False) -> list[FileAssetResponse]:
if not assets:
return []
asset_ids = [asset.id for asset in assets]
version_ids = [asset.current_version_id for asset in assets if asset.current_version_id]
if len(version_ids) != len(assets):
raise FileStorageError("File has no current version")
version_blob_rows: list[tuple[FileVersion, FileBlob]] = []
for chunk in _chunks(version_ids):
version_blob_rows.extend(
session.query(FileVersion, FileBlob)
.join(FileBlob, FileBlob.id == FileVersion.blob_id)
.filter(FileVersion.id.in_(chunk))
.all()
)
versions_by_id = {version.id: version for version, _blob in version_blob_rows}
blobs_by_version_id = {version.id: blob for version, blob in version_blob_rows}
shares_by_asset_id: dict[str, list[FileShareResponse]] = {asset_id: [] for asset_id in asset_ids}
if include_shares:
for chunk in _chunks(asset_ids):
share_rows = (
session.query(FileShare)
.filter(FileShare.file_asset_id.in_(chunk))
.order_by(FileShare.created_at.desc())
.all()
)
for row in share_rows:
shares_by_asset_id.setdefault(row.file_asset_id, []).append(
FileShareResponse(
id=row.id,
target_type=row.target_type,
target_id=row.target_id,
permission=row.permission,
created_at=row.created_at.isoformat(),
revoked_at=row.revoked_at.isoformat() if row.revoked_at else None,
)
)
sent_asset_ids: set[str] = set()
for chunk in _chunks(asset_ids):
sent_rows = (
session.query(CampaignAttachmentUse.file_asset_id)
.filter(CampaignAttachmentUse.file_asset_id.in_(chunk), CampaignAttachmentUse.use_stage == "sent")
.distinct()
.all()
)
sent_asset_ids.update(row[0] for row in sent_rows)
responses: list[FileAssetResponse] = []
for asset in assets:
version = versions_by_id.get(asset.current_version_id or "")
blob = blobs_by_version_id.get(asset.current_version_id or "")
if not version or not blob:
raise FileStorageError("File version not found")
responses.append(
FileAssetResponse(
id=asset.id,
tenant_id=asset.tenant_id,
owner_type=asset.owner_type,
owner_id=_owner_id(asset),
display_path=asset.display_path,
filename=asset.filename,
description=asset.description,
size_bytes=blob.size_bytes,
content_type=blob.content_type,
checksum_sha256=blob.checksum_sha256,
version_id=version.id,
created_at=asset.created_at.isoformat(),
updated_at=asset.updated_at.isoformat(),
deleted_at=asset.deleted_at.isoformat() if asset.deleted_at else None,
audit_relevant=asset.id in sent_asset_ids,
metadata=asset.metadata_ or {},
shares=shares_by_asset_id.get(asset.id, []),
)
)
return responses
def _chunks(values: list[str], size: int = 900):
for index in range(0, len(values), size):
yield values[index:index + size]
def _folder_owner_id(folder: FileFolder) -> str:
return folder.owner_user_id if folder.owner_type == "user" else folder.owner_group_id # type: ignore[return-value]
@@ -234,7 +314,7 @@ def list_file_spaces(
]
group_ids = user_group_ids(session, tenant_id=principal.tenant_id, user_id=principal.user.id, include_admin_groups=_is_admin(principal))
if group_ids:
groups = session.query(Group).filter(Group.tenant_id == principal.tenant_id, Group.id.in_(group_ids)).order_by(Group.name.asc()).all()
groups = group_refs_for_ids(tenant_id=principal.tenant_id, group_ids=group_ids)
spaces.extend(
FileSpaceResponse(
id=f"group:{group.id}",
@@ -337,7 +417,7 @@ def list_files(
path_prefix=path_prefix,
is_admin=_is_admin(principal),
)
return FileListResponse(files=[_asset_response(session, asset, include_shares=True) for asset in assets])
return FileListResponse(files=_asset_list_response(session, assets, include_shares=True))
@router.post("/upload", response_model=FileUploadResponse)
@@ -538,6 +618,48 @@ def create_share(
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)
def bulk_rename(
payload: RenameRequest,

View File

@@ -2,15 +2,22 @@ from __future__ import annotations
from typing import Any
_runtime_registry: object | None = None
_runtime_settings: object | None = None
def configure_runtime(*, settings: object | None = None) -> None:
global _runtime_settings
def configure_runtime(*, registry: object | None = None, settings: object | None = None) -> None:
global _runtime_registry, _runtime_settings
if registry is not None:
_runtime_registry = registry
if settings is not None:
_runtime_settings = settings
def get_registry() -> object | None:
return _runtime_registry
def get_settings() -> object:
if _runtime_settings is not None:
return _runtime_settings

View File

@@ -113,6 +113,18 @@ class FileShareRequest(BaseModel):
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):
file_ids: list[str] = Field(default_factory=list)
folder_paths: list[str] = Field(default_factory=list)

View File

@@ -2,33 +2,50 @@ from __future__ import annotations
from sqlalchemy.orm import Session
from govoplan_core.db.models import Group, UserGroupMembership
from govoplan_core.core.access import (
CAPABILITY_ACCESS_DIRECTORY,
AccessDirectory,
GroupRef,
)
from govoplan_core.core.runtime import get_registry
from govoplan_files.backend.storage.common import FileStorageError
def _access_directory() -> AccessDirectory:
registry = get_registry()
if registry is None or not hasattr(registry, "has_capability") or not registry.has_capability(CAPABILITY_ACCESS_DIRECTORY):
raise FileStorageError("Access directory capability is not configured")
capability = registry.require_capability(CAPABILITY_ACCESS_DIRECTORY)
if not isinstance(capability, AccessDirectory):
raise FileStorageError("Access directory capability is invalid")
return capability
def group_refs_for_ids(*, tenant_id: str, group_ids: list[str]) -> list[GroupRef]:
if not group_ids:
return []
groups = _access_directory().get_groups(group_ids)
return sorted(
[group for group in groups.values() if group.tenant_id == tenant_id],
key=lambda group: group.name.casefold(),
)
def user_group_ids(session: Session, *, tenant_id: str, user_id: str, include_admin_groups: bool = False) -> list[str]:
del session
directory = _access_directory()
if include_admin_groups:
return [row.id for row in session.query(Group).filter(Group.tenant_id == tenant_id).order_by(Group.name.asc()).all()]
return [
row.group_id
for row in session.query(UserGroupMembership)
.filter(UserGroupMembership.tenant_id == tenant_id, UserGroupMembership.user_id == user_id)
.all()
]
return [group.id for group in directory.groups_for_tenant(tenant_id)]
return [group.id for group in directory.groups_for_user(user_id, tenant_id=tenant_id)]
def ensure_group_access(session: Session, *, tenant_id: str, group_id: str, user_id: str, is_admin: bool = False) -> None:
group = session.get(Group, group_id)
group = _access_directory().get_group(group_id)
if not group or group.tenant_id != tenant_id:
raise FileStorageError("Group not found")
if is_admin:
return
membership = (
session.query(UserGroupMembership)
.filter(UserGroupMembership.tenant_id == tenant_id, UserGroupMembership.user_id == user_id, UserGroupMembership.group_id == group_id)
.one_or_none()
)
if membership is None:
if group_id not in user_group_ids(session, tenant_id=tenant_id, user_id=user_id):
raise FileStorageError("No access to this group file space")
@@ -42,3 +59,21 @@ def ensure_owner_access(session: Session, *, tenant_id: str, owner_type: str, ow
ensure_group_access(session, tenant_id=tenant_id, group_id=owner_id, user_id=user_id, is_admin=is_admin)
return
raise FileStorageError("Files must be owned by a user or group")
def ensure_share_target_exists(*, tenant_id: str, target_type: str, target_id: str) -> None:
target_type = target_type.lower().strip()
if target_type == "user":
user = _access_directory().get_user(target_id)
if not user or user.tenant_id != tenant_id or user.status != "active":
raise FileStorageError("User not found")
return
if target_type == "group":
group = _access_directory().get_group(target_id)
if not group or group.tenant_id != tenant_id or group.status != "active":
raise FileStorageError("Group not found")
return
if target_type == "tenant":
if target_id != tenant_id:
raise FileStorageError("Tenant not found")
return

View File

@@ -11,7 +11,7 @@ from sqlalchemy.orm import Session
from govoplan_files.backend.db.models import FileAsset
from govoplan_files.backend.storage.common import FileConflictResolution, FileStorageError, UploadedStoredFile
from govoplan_files.backend.storage.backends import StorageBackendError, get_storage_backend
from govoplan_files.backend.storage.files import create_file_asset, current_version_and_blob
from govoplan_files.backend.storage.files import create_file_asset, current_versions_and_blobs
from govoplan_files.backend.storage.paths import filename_from_path, normalize_folder, normalize_logical_path
@@ -45,9 +45,11 @@ def _read_zip_member(
def create_zip_file(session: Session, assets: Iterable[FileAsset], output_path: str | Path) -> None:
backend = get_storage_backend()
asset_list = list(assets)
version_blobs = current_versions_and_blobs(session, asset_list)
with zipfile.ZipFile(output_path, mode="w", compression=zipfile.ZIP_DEFLATED) as archive:
for asset in assets:
_version, blob = current_version_and_blob(session, asset)
for asset in asset_list:
_version, blob = version_blobs[asset.id]
info = zipfile.ZipInfo(asset.display_path)
info.compress_type = zipfile.ZIP_DEFLATED
with archive.open(info, "w") as member:

View File

@@ -4,8 +4,6 @@ from dataclasses import dataclass, field
from pathlib import Path
from typing import Iterable, Protocol
import boto3
from govoplan_files.backend.runtime import settings
@@ -94,6 +92,10 @@ class S3StorageBackend:
@property
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(
"s3",
endpoint_url=self.endpoint_url,

View File

@@ -13,7 +13,9 @@ from typing import Any, Iterator
from sqlalchemy.orm import Session
from govoplan_files.backend.db.models import FileAsset
from govoplan_files.backend.storage.files import current_version_and_blob, list_assets_for_user, read_asset_bytes
from govoplan_files.backend.storage.backends import StorageBackendError, get_storage_backend
from govoplan_files.backend.storage.common import FileStorageError
from govoplan_files.backend.storage.files import current_versions_and_blobs, list_assets_for_user
from govoplan_files.backend.storage.paths import normalize_folder, normalize_logical_path, safe_storage_component
@@ -172,6 +174,8 @@ def prepare_campaign_snapshot(
owner_id = _asset_owner_id(asset)
if owner_id:
assets_by_owner[(asset.owner_type, owner_id)].append(asset)
version_blobs = current_versions_and_blobs(session, shared_assets)
backend = get_storage_backend() if include_bytes else None
manifest: dict[str, ManagedAttachmentFile] = {}
prepared_by_id: dict[str, tuple[str, str]] = {}
@@ -206,11 +210,14 @@ def prepare_campaign_snapshot(
continue
target = _safe_local_target(local_root, relative_path)
target.parent.mkdir(parents=True, exist_ok=True)
version, blob = version_blobs[asset.id]
if include_bytes:
data, version, blob = read_asset_bytes(session, asset)
try:
data = backend.get_bytes(blob.storage_key) if backend else b""
except StorageBackendError as exc:
raise FileStorageError(str(exc)) from exc
target.write_bytes(data)
else:
version, blob = current_version_and_blob(session, asset)
target.touch()
local_key = str(target.resolve())
manifest[local_key] = ManagedAttachmentFile(

View File

@@ -2,14 +2,15 @@ from __future__ import annotations
from collections import defaultdict
from pathlib import PurePosixPath
from typing import Iterable
from typing import Any, Iterable
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.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_versions_and_blobs, list_assets_for_user
CampaignJobLike = Any
def _candidate_match_keys(raw_match: str) -> set[str]:
@@ -27,7 +28,7 @@ def _attachment_use_key(*, job_id: str, file_version_id: str, filename_used: str
return job_id, file_version_id, filename_used, stage
def _known_use_keys_for_jobs(session: Session, jobs: Iterable[CampaignJob], *, stage: str) -> set[AttachmentUseKey]:
def _known_use_keys_for_jobs(session: Session, jobs: Iterable[CampaignJobLike], *, stage: str) -> set[AttachmentUseKey]:
job_ids = {job.id for job in jobs if job.id}
if not job_ids:
return set()
@@ -70,13 +71,13 @@ def _known_use_keys_for_jobs(session: Session, jobs: Iterable[CampaignJob], *, s
return keys
def _known_use_keys(session: Session, job: CampaignJob, *, stage: str) -> set[AttachmentUseKey]:
def _known_use_keys(session: Session, job: CampaignJobLike, *, stage: str) -> set[AttachmentUseKey]:
return _known_use_keys_for_jobs(session, [job], stage=stage)
def _add_use(
session: Session,
job: CampaignJob,
job: CampaignJobLike,
*,
asset: FileAsset,
version: FileVersion,
@@ -116,7 +117,7 @@ def _add_use(
def record_campaign_attachment_uses_for_jobs(
session: Session,
jobs: Iterable[CampaignJob],
jobs: Iterable[CampaignJobLike],
*,
stage: str = "built",
) -> None:
@@ -202,6 +203,7 @@ def record_campaign_attachment_uses_for_jobs(
)
assets_by_campaign: dict[tuple[str, str], dict[str, FileAsset]] = {}
version_blobs_by_campaign: dict[tuple[str, str], dict[str, tuple[FileVersion, FileBlob]]] = {}
for job_id, attachments in fallback_attachments_by_job.items():
job = job_by_id[job_id]
campaign_key = (job.tenant_id, job.campaign_id)
@@ -219,6 +221,8 @@ def record_campaign_attachment_uses_for_jobs(
by_key[asset.display_path.strip("/")] = asset
by_key.setdefault(asset.filename, asset)
assets_by_campaign[campaign_key] = by_key
version_blobs_by_campaign[campaign_key] = current_versions_and_blobs(session, assets)
version_blobs = version_blobs_by_campaign[campaign_key]
for attachment in attachments:
matches = attachment.get("matches") if isinstance(attachment.get("matches"), list) else []
@@ -228,7 +232,10 @@ def record_campaign_attachment_uses_for_jobs(
asset = next((by_key[key] for key in _candidate_match_keys(raw) if key in by_key), None)
if not asset:
continue
version, blob = current_version_and_blob(session, asset)
version_blob = version_blobs.get(asset.id)
if not version_blob:
continue
version, blob = version_blob
_add_use(
session,
job,
@@ -241,13 +248,13 @@ def record_campaign_attachment_uses_for_jobs(
)
def record_campaign_attachment_uses_for_job(session: Session, job: CampaignJob, *, stage: str = "built") -> None:
def record_campaign_attachment_uses_for_job(session: Session, job: CampaignJobLike, *, stage: str = "built") -> None:
"""Record immutable managed file versions used by one built/sent job."""
record_campaign_attachment_uses_for_jobs(session, [job], stage=stage)
def mark_job_attachment_uses_sent(session: Session, job: CampaignJob) -> None:
def mark_job_attachment_uses_sent(session: Session, job: CampaignJobLike) -> None:
record_campaign_attachment_uses_for_job(session, job, stage="built")
# Sessions use autoflush=False. Flush any compatibility-built evidence so
# the following query can copy it to the sent stage in the same call.

View File

@@ -9,16 +9,30 @@ from uuid import uuid4
from sqlalchemy import or_
from sqlalchemy.orm import Session
from govoplan_core.db.models import Group, Tenant, User
from govoplan_campaign.backend.db.models import Campaign
from govoplan_core.core.campaigns import CAPABILITY_CAMPAIGNS_ACCESS, CampaignAccessProvider
from govoplan_files.backend.db.models import CampaignAttachmentUse, FileAsset, FileBlob, FileShare, FileVersion
from govoplan_files.backend.runtime import settings
from govoplan_files.backend.storage.access import ensure_owner_access, user_group_ids
from govoplan_files.backend.runtime import get_registry, settings
from govoplan_files.backend.storage.access import ensure_owner_access, ensure_share_target_exists, user_group_ids
from govoplan_files.backend.storage.backends import StorageBackendError, get_storage_backend
from govoplan_files.backend.storage.common import FileConflictResolution, FileStorageError, UploadedStoredFile, utcnow
from govoplan_files.backend.storage.paths import filename_from_path, join_folder_filename, normalize_folder, normalize_logical_path, safe_storage_component
def _campaign_access_provider() -> CampaignAccessProvider:
registry = get_registry()
if registry is None or not hasattr(registry, "has_capability") or not registry.has_capability(CAPABILITY_CAMPAIGNS_ACCESS):
raise FileStorageError("Campaign module is not installed")
capability = registry.require_capability(CAPABILITY_CAMPAIGNS_ACCESS)
if not isinstance(capability, CampaignAccessProvider):
raise FileStorageError("Campaign access capability is invalid")
return capability
def _ensure_campaign_exists(session: Session, *, tenant_id: str, campaign_id: str) -> None:
if not _campaign_access_provider().campaign_exists(session, tenant_id=tenant_id, campaign_id=campaign_id):
raise FileStorageError("Campaign not found")
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)
if owner_type == "user":
@@ -256,6 +270,32 @@ def current_version_and_blob(session: Session, asset: FileAsset) -> tuple[FileVe
return version, blob
def current_versions_and_blobs(session: Session, assets: Iterable[FileAsset]) -> dict[str, tuple[FileVersion, FileBlob]]:
asset_list = list(assets)
if not asset_list:
return {}
version_ids = [asset.current_version_id for asset in asset_list if asset.current_version_id]
if len(version_ids) != len(asset_list):
raise FileStorageError("File has no current version")
rows: list[tuple[FileVersion, FileBlob]] = []
for chunk in _chunks(version_ids):
rows.extend(
session.query(FileVersion, FileBlob)
.join(FileBlob, FileBlob.id == FileVersion.blob_id)
.filter(FileVersion.id.in_(chunk))
.all()
)
by_version_id = {version.id: (version, blob) for version, blob in rows}
result: dict[str, tuple[FileVersion, FileBlob]] = {}
for asset in asset_list:
version_blob = by_version_id.get(asset.current_version_id or "")
if not version_blob:
raise FileStorageError("File version not found")
result[asset.id] = version_blob
return result
def read_asset_bytes(session: Session, asset: FileAsset) -> tuple[bytes, FileVersion, FileBlob]:
version, blob = current_version_and_blob(session, asset)
backend = get_storage_backend()
@@ -283,22 +323,10 @@ def share_file(
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 in {"user", "group", "tenant"}:
ensure_share_target_exists(tenant_id=tenant_id, target_type=target_type, target_id=target_id)
if target_type == "campaign":
campaign = session.get(Campaign, target_id)
if not campaign or campaign.tenant_id != tenant_id:
raise FileStorageError("Campaign not found")
_ensure_campaign_exists(session, tenant_id=tenant_id, campaign_id=target_id)
existing = (
session.query(FileShare)
.filter(
@@ -326,6 +354,66 @@ def share_file(
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 in {"user", "group", "tenant"}:
ensure_share_target_exists(tenant_id=tenant_id, target_type=target_type, target_id=target_id)
if target_type == "campaign":
_ensure_campaign_exists(session, tenant_id=tenant_id, campaign_id=target_id)
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:
count = 0
now = utcnow()
@@ -354,6 +442,11 @@ def _asset_owner_id(asset: FileAsset) -> str:
raise FileStorageError("File has no valid owner")
def _chunks(values: list[str], size: int = 900):
for index in range(0, len(values), size):
yield values[index:index + size]
def _active_asset_exists(session: Session, *, tenant_id: str, owner_type: str, owner_id: str, path: str, exclude_asset_id: str | None = None) -> bool:
return _active_asset_at_path(
session,

View File

@@ -33,6 +33,7 @@ from govoplan_files.backend.storage.files import (
asset_is_audit_relevant,
create_file_asset,
current_version_and_blob,
current_versions_and_blobs,
get_asset_for_user,
list_assets_for_user,
read_asset_bytes,
@@ -64,6 +65,7 @@ __all__ = [
"create_folder",
"create_zip_file",
"current_version_and_blob",
"current_versions_and_blobs",
"ensure_group_access",
"ensure_owner_access",
"extract_zip_upload",

View File

@@ -69,17 +69,13 @@ def transfer_selection(
if target_folder == folder_path or target_folder.startswith(f"{folder_path}/"):
raise FileStorageError("Cannot move a folder into itself or one of its child folders")
assets_by_id: dict[str, FileAsset] = {}
for file_id in file_ids:
asset = get_asset_for_user(
session,
tenant_id=tenant_id,
user_id=user_id,
asset_id=file_id,
require_write=operation == "move",
is_admin=is_admin,
)
assets_by_id[asset.id] = asset
assets_by_id = _selected_assets_for_owner(
session,
tenant_id=tenant_id,
owner_type=source_owner_type,
owner_id=source_owner_id,
file_ids=file_ids,
)
folder_asset_targets: dict[str, str] = {}
folder_target_paths: dict[str, str] = {}
@@ -297,6 +293,33 @@ def _collapse_folder_roots(folder_paths: list[str]) -> list[str]:
return collapsed
def _selected_assets_for_owner(
session: Session,
*,
tenant_id: str,
owner_type: str,
owner_id: str,
file_ids: list[str],
) -> dict[str, FileAsset]:
selected_file_ids = list(dict.fromkeys(file_ids))
if not selected_file_ids:
return {}
assets = {
asset.id: asset
for asset in _asset_query_for_owner(
session,
tenant_id=tenant_id,
owner_type=owner_type,
owner_id=owner_id,
)
.filter(FileAsset.id.in_(selected_file_ids), FileAsset.deleted_at.is_(None))
.all()
}
if len(assets) != len(selected_file_ids):
raise FileStorageError("File not found")
return assets
def _path_under_root(path: str, root: str) -> bool:
normalized = normalize_logical_path(path)
return normalized == root or normalized.startswith(f"{root}/")
@@ -349,13 +372,26 @@ def rename_selection(
if mode == "direct" and (len(selected_file_ids) + len(selected_folder_roots)) != 1:
raise FileStorageError("Direct rename requires exactly one selected item")
assets: dict[str, FileAsset] = {}
for file_id in selected_file_ids:
asset = get_asset_for_user(session, tenant_id=tenant_id, user_id=user_id, asset_id=file_id, require_write=True, is_admin=is_admin)
assets[asset.id] = asset
owner_type_norm = owner_type.lower().strip() if owner_type else None
owner_id_norm = owner_id
assets: dict[str, FileAsset] = {}
if selected_file_ids:
if owner_type_norm and owner_id_norm:
ensure_owner_access(session, tenant_id=tenant_id, owner_type=owner_type_norm, owner_id=owner_id_norm, user_id=user_id, is_admin=is_admin)
assets.update(
_selected_assets_for_owner(
session,
tenant_id=tenant_id,
owner_type=owner_type_norm,
owner_id=owner_id_norm,
file_ids=selected_file_ids,
)
)
else:
for file_id in selected_file_ids:
asset = get_asset_for_user(session, tenant_id=tenant_id, user_id=user_id, asset_id=file_id, require_write=True, is_admin=is_admin)
assets[asset.id] = asset
folder_rows_by_path: dict[str, FileFolder] = {}
affected_folder_paths: set[str] = set()
if selected_folder_roots and owner_type_norm and owner_id_norm:

View File

@@ -1,6 +1,6 @@
{
"name": "@govoplan/files-webui",
"version": "0.1.0",
"version": "0.1.6",
"private": true,
"type": "module",
"main": "src/index.ts",
@@ -21,6 +21,11 @@
"react-dom": "^19.0.0",
"react-router-dom": "^7.1.1",
"lucide-react": "^0.555.0",
"@govoplan/core-webui": "^0.1.0"
"@govoplan/core-webui": "^0.1.6"
},
"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, type FilesManagedFileLinkTarget } from "@govoplan/core-webui";
export type FileSpace = {
id: string;
@@ -40,6 +40,7 @@ export type ManagedFile = {
export type FileListResponse = { files: ManagedFile[] };
export type FileSpacesResponse = { spaces: FileSpace[] };
export type FileUploadResponse = { files: ManagedFile[] };
export type FileUploadProgress = { loaded: number; total?: number; percentage: number | null };
export type FileFolder = {
id: string;
tenant_id: string;
@@ -102,7 +103,16 @@ export function listFiles(settings: ApiSettings, params: { owner_type?: string;
export async function uploadFiles(
settings: ApiSettings,
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> {
const form = new FormData();
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.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.onProgress) return uploadFilesWithProgress(settings, form, options.onProgress);
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> {
return apiFetch<BulkDeleteResponse>(settings, `/api/v1/files/${fileId}`, { method: "DELETE" });
}
@@ -124,13 +179,26 @@ 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 }) });
}
export function shareFileWithCampaign(settings: ApiSettings, fileId: string, campaignId: string): Promise<FileShare> {
return apiFetch<FileShare>(settings, `/api/v1/files/${fileId}/shares`, {
export type FileBulkShareResponse = { shares: FileShare[]; shared_count: number };
export function shareFilesWithTarget(settings: ApiSettings, fileIds: string[], target: FilesManagedFileLinkTarget): Promise<FileBulkShareResponse> {
return apiFetch<FileBulkShareResponse>(settings, "/api/v1/files/bulk-shares", {
method: "POST",
body: JSON.stringify({ target_type: "campaign", target_id: campaignId, permission: "read" })
body: JSON.stringify({ file_ids: fileIds, target_type: target.type, target_id: target.id, permission: target.permission ?? "read" })
});
}
export function shareFilesWithCampaign(settings: ApiSettings, fileIds: string[], campaignId: string): Promise<FileBulkShareResponse> {
return shareFilesWithTarget(settings, fileIds, { type: "campaign", id: campaignId, label: "campaign" });
}
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(
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 }

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 { 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 {
Button,
ConfirmDialog,
DismissibleAlert,
FieldLabel,
FileDropZone,
FormField,
LoadingIndicator,
ToggleSwitch,
@@ -75,6 +76,11 @@ import { useFileTreeState } from "./hooks/useFileTreeState";
import { useFileDialogs } from "./hooks/useFileDialogs";
import { useFileDragDropState } from "./hooks/useFileDragDropState";
type UploadPhase = "idle" | "uploading" | "unpacking" | "finalizing";
const DEFAULT_FILE_LIST_ROW_HEIGHT = 58;
const FILE_LIST_OVERSCAN_ROWS = 8;
export default function FilesPage({ settings, auth }: { settings: ApiSettings; auth: AuthInfo }) {
const canDownload = hasScope(auth, "files:download");
const canUpload = hasScope(auth, "files:upload");
@@ -98,9 +104,12 @@ export default function FilesPage({ settings, auth }: { settings: ApiSettings; a
const [unmatchedCount, setUnmatchedCount] = useState<number | null>(null);
const [unpackZip, setUnpackZip] = 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 [error, setError] = useState("");
const { dragActive, setDragActive, internalDrag, setInternalDrag, dropTargetKey, setDropTargetKey, clearDropState: clearDragDropState } = useFileDragDropState();
const { setDragActive, internalDrag, setInternalDrag, dropTargetKey, setDropTargetKey, clearDropState: clearDragDropState } = useFileDragDropState();
const {
dialog,
setDialog,
@@ -130,13 +139,33 @@ export default function FilesPage({ settings, auth }: { settings: ApiSettings; a
const [renameSuffix, setRenameSuffix] = useState("");
const [renameRecursive, setRenameRecursive] = useState(false);
const [renamePreview, setRenamePreview] = useState<RenameResponse | null>(null);
const fileInputRef = useRef<HTMLInputElement | null>(null);
const visibleFiles = searchActive && searchResults ? searchResults : files;
const explorerEntries = useMemo(() => {
const entries = buildExplorerEntries(visibleFiles, folders, currentFolder, searchActive);
return sortExplorerEntries(entries, sortColumn, sortDirection);
}, [visibleFiles, folders, currentFolder, searchActive, sortColumn, sortDirection]);
const fileListViewportRef = useRef<HTMLDivElement | null>(null);
const fileListMeasureRowRef = useRef<HTMLDivElement | null>(null);
const [fileListViewportHeight, setFileListViewportHeight] = useState(0);
const [fileListScrollTop, setFileListScrollTop] = useState(0);
const [fileListRowHeight, setFileListRowHeight] = useState(DEFAULT_FILE_LIST_ROW_HEIGHT);
const virtualExplorerRows = useMemo(() => {
const rowHeight = Math.max(1, fileListRowHeight);
const entryScrollTop = Math.max(0, fileListScrollTop - rowHeight);
const viewportHeight = Math.max(fileListViewportHeight, rowHeight * FILE_LIST_OVERSCAN_ROWS);
const startIndex = Math.max(0, Math.floor(entryScrollTop / rowHeight) - FILE_LIST_OVERSCAN_ROWS);
const endIndex = Math.min(
explorerEntries.length,
Math.ceil((entryScrollTop + viewportHeight) / rowHeight) + FILE_LIST_OVERSCAN_ROWS
);
return {
startIndex,
topSpacerHeight: startIndex * rowHeight,
bottomSpacerHeight: Math.max(0, (explorerEntries.length - endIndex) * rowHeight),
entries: explorerEntries.slice(startIndex, endIndex)
};
}, [explorerEntries, fileListRowHeight, fileListScrollTop, fileListViewportHeight]);
const visibleEntryKeys = useMemo(() => explorerEntries.map(entrySelectionKey), [explorerEntries]);
const {
selectedFileIds,
@@ -168,6 +197,47 @@ export default function FilesPage({ settings, auth }: { settings: ApiSettings; a
const activeDialogSpace = activeDialogTarget ? spaces.find((space) => space.id === activeDialogTarget.spaceId) ?? null : null;
const downloadLabel = selectedDownloadFileIds.length > 1 ? "Download ZIP" : "Download";
useEffect(() => {
const viewport = fileListViewportRef.current;
if (!viewport) return undefined;
const updateViewportHeight = () => {
setFileListViewportHeight(viewport.clientHeight);
setFileListScrollTop(viewport.scrollTop);
};
updateViewportHeight();
if (typeof ResizeObserver === "undefined") return undefined;
const observer = new ResizeObserver(updateViewportHeight);
observer.observe(viewport);
return () => observer.disconnect();
}, []);
useEffect(() => {
const row = fileListMeasureRowRef.current;
if (!row) return undefined;
const updateRowHeight = () => {
const measuredHeight = row.getBoundingClientRect().height;
if (measuredHeight > 0) setFileListRowHeight(Math.round(measuredHeight));
};
updateRowHeight();
if (typeof ResizeObserver === "undefined") return undefined;
const observer = new ResizeObserver(updateRowHeight);
observer.observe(row);
return () => observer.disconnect();
}, [activeSpaceId, currentFolder]);
useEffect(() => {
const viewport = fileListViewportRef.current;
if (!viewport) return;
viewport.scrollTop = 0;
setFileListScrollTop(0);
}, [activeSpaceId, currentFolder, searchActive, searchResults, sortColumn, sortDirection]);
async function loadSpaces() {
setBusy(true);
setError("");
@@ -275,6 +345,9 @@ export default function FilesPage({ settings, auth }: { settings: ApiSettings; a
function closeDialog() {
closeRawDialog();
setNewFolderError("");
setUploadActive(false);
setUploadPhase("idle");
setUploadProgress(null);
}
function updateActiveDialogFolder(spaceId: string, folderPath: string) {
@@ -309,7 +382,11 @@ export default function FilesPage({ settings, auth }: { settings: ApiSettings; a
return;
}
}
const uploadsZipArchive = unpackZip && selected.some((file) => file.name.toLowerCase().endsWith(".zip"));
setBusy(true);
setUploadActive(true);
setUploadPhase("uploading");
setUploadProgress(0);
setError("");
setMessage(`Uploading ${selected.length} file(s)…`);
try {
@@ -319,8 +396,17 @@ export default function FilesPage({ settings, auth }: { settings: ApiSettings; a
path: target.folderPath,
unpack_zip: unpackZip,
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"}.`);
closeDialog();
setConflictDialog(null);
@@ -331,7 +417,9 @@ export default function FilesPage({ settings, auth }: { settings: ApiSettings; a
setMessage("");
} finally {
setBusy(false);
if (fileInputRef.current) fileInputRef.current.value = "";
setUploadActive(false);
setUploadPhase("idle");
setUploadProgress(null);
}
}
@@ -386,25 +474,29 @@ export default function FilesPage({ settings, auth }: { settings: ApiSettings; a
}
}
async function runPatternSearch() {
if (!activeSpace || !searchPattern.trim()) {
async function runPatternSearch(patternOverride = searchPattern, caseSensitiveOverride = searchCaseSensitive) {
const trimmedPattern = patternOverride.trim();
if (!activeSpace || !trimmedPattern) {
await clearSearch();
return;
}
const caseSensitive = caseSensitiveOverride;
setBusy(true);
setError("");
setMessage("");
try {
const response = await resolveFilePatterns(settings, {
patterns: [searchPattern.trim()],
patterns: [trimmedPattern],
owner_type: activeSpace.owner_type,
owner_id: activeSpace.owner_id,
path_prefix: currentFolder,
include_unmatched: true,
case_sensitive: searchCaseSensitive
case_sensitive: caseSensitive
});
setSearchResults(response.patterns.flatMap((pattern) => pattern.matches));
setSearchActive(true);
setSearchPattern(trimmedPattern);
setSearchCaseSensitive(caseSensitive);
setUnmatchedCount(response.unmatched.length);
setSelectedFileIds(new Set());
setSelectedFolderPaths(new Set());
@@ -1127,6 +1219,83 @@ export default function FilesPage({ settings, auth }: { settings: ApiSettings; a
</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;
function renderExplorerEntry(entry: ExplorerEntry, rowIndex: number) {
const entryDropTarget = entry.kind === "folder" && activeSpace ? { spaceId: activeSpace.id, folderPath: entry.path } : null;
const isDropTarget = entryDropTarget ? dropTargetKey === dropTargetId(entryDropTarget) : false;
return entry.kind === "folder" ? (
<div
key={entry.id}
className={`file-list-row folder-row ${isEntrySelected(entry) ? "is-selected" : ""} ${isDropTarget ? "is-drop-target" : ""}`}
role="row"
aria-rowindex={rowIndex}
tabIndex={0}
draggable
onDragStart={(event) => handleInternalDragStart(entry, event)}
onDragEnd={() => { setInternalDrag(null); clearDropState(); }}
onDragOver={(event) => entryDropTarget && handleDropTargetDragOver(event, entryDropTarget)}
onDragLeave={clearDropState}
onDrop={(event) => entryDropTarget && void handleDropOnTarget(event, entryDropTarget)}
onMouseDown={preventTextSelectionOnShift}
onClick={(event) => handleEntrySelection(entry, event)}
onDoubleClick={() => { if (!busy && activeSpace) openFolder(activeSpace.id, entry.path); }}
onContextMenu={(event) => openContextMenu(event, "folder", entry)}
onKeyDown={(event) => handleEntryKeyDown(entry, event)}
>
<div className="file-list-name-cell">
<div className="file-list-name">
<Folder className="file-row-icon" size={20} aria-hidden="true" />
<span><strong>{entry.name}</strong><small>{folderContentLabel(entry)}</small></span>
</div>
</div>
<span>{formatBytes(entry.totalSize)}</span>
<span className="file-row-tail"><span>{formatDate(entry.updatedAt)}</span></span>
</div>
) : (
<div
key={entry.id}
className={`file-list-row file-row ${isEntrySelected(entry) ? "is-selected" : ""}`}
role="row"
aria-rowindex={rowIndex}
tabIndex={0}
draggable
onDragStart={(event) => handleInternalDragStart(entry, event)}
onDragEnd={() => { setInternalDrag(null); clearDropState(); }}
onMouseDown={preventTextSelectionOnShift}
onClick={(event) => handleEntrySelection(entry, event)}
onDoubleClick={() => { if (!busy) void downloadFile(settings, entry.file); }}
onContextMenu={(event) => openContextMenu(event, "file", entry)}
onKeyDown={(event) => handleEntryKeyDown(entry, event)}
>
<div className="file-list-name-cell">
<div className="file-list-name">
<File className="file-row-icon" size={20} aria-hidden="true" />
<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>
<span>{formatBytes(entry.file.size_bytes)}</span>
<span className="file-row-tail"><span>{formatDate(entry.file.updated_at)}</span></span>
</div>
);
}
return (
<div className="workspace-data-page module-entry-page file-manager-page file-manager-fullscreen">
{error && (
@@ -1199,13 +1368,15 @@ export default function FilesPage({ settings, auth }: { settings: ApiSettings; a
</span>
))}
</nav>
<div className="file-search-row">
<Search size={17} aria-hidden="true" />
<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(); }} />
<ToggleSwitch label="Case sensitive" checked={searchCaseSensitive} onChange={setSearchCaseSensitive} disabled={busy} />
<Button onClick={() => void runPatternSearch()} disabled={busy || !activeSpace}>Search</Button>
{searchActive && <Button onClick={() => void clearSearch()} disabled={busy}>Clear</Button>}
</div>
<FileSearchRow
value={searchPattern}
caseSensitive={searchCaseSensitive}
busy={busy}
searchActive={searchActive}
disabled={!activeSpace}
onSearch={(patternValue, caseSensitiveValue) => void runPatternSearch(patternValue, caseSensitiveValue)}
onClear={() => void clearSearch()}
/>
<div className="file-list-meta">
<span>{selectedSummary}</span>
<span>{explorerEntries.filter((entry) => entry.kind === "folder").length} folder(s) · {explorerEntries.filter((entry) => entry.kind === "file").length} file(s)</span>
@@ -1222,20 +1393,24 @@ export default function FilesPage({ settings, auth }: { settings: ApiSettings; a
<div
className="file-list-drop-target"
ref={fileListViewportRef}
onScroll={(event) => setFileListScrollTop(event.currentTarget.scrollTop)}
onContextMenu={(event) => openContextMenu(event, "empty")}
onClick={(event) => {
if (event.target === event.currentTarget) applySelectionKeys(new Set<EntrySelectionKey>());
}}
>
<div className="file-list-table" role="table" aria-label="Managed files">
<div className="file-list-table" role="table" aria-label="Managed files" aria-rowcount={explorerEntries.length + 1}>
{(() => {
const normalizedCurrentFolder = normalizeFolder(currentFolder);
const canOpenParent = Boolean(normalizedCurrentFolder && activeSpace);
const targetParentFolder = parentFolderPath(normalizedCurrentFolder);
return (
<div
ref={fileListMeasureRowRef}
className={`file-list-row folder-row file-parent-row ${canOpenParent ? "" : "is-disabled"}`}
role="row"
aria-rowindex={1}
tabIndex={canOpenParent ? 0 : -1}
aria-disabled={!canOpenParent}
aria-label={canOpenParent ? `Open parent folder ${targetParentFolder || activeSpace?.label || "root"}` : "Already at the root folder"}
@@ -1265,62 +1440,13 @@ export default function FilesPage({ settings, auth }: { settings: ApiSettings; a
{explorerEntries.length === 0 && (
<div className="file-list-empty">This folder is empty. Use Upload or Create Folder to add content.</div>
)}
{explorerEntries.map((entry) => {
const entryDropTarget = entry.kind === "folder" && activeSpace ? { spaceId: activeSpace.id, folderPath: entry.path } : null;
const isDropTarget = entryDropTarget ? dropTargetKey === dropTargetId(entryDropTarget) : false;
return entry.kind === "folder" ? (
<div
key={entry.id}
className={`file-list-row folder-row ${isEntrySelected(entry) ? "is-selected" : ""} ${isDropTarget ? "is-drop-target" : ""}`}
role="row"
tabIndex={0}
draggable
onDragStart={(event) => handleInternalDragStart(entry, event)}
onDragEnd={() => { setInternalDrag(null); clearDropState(); }}
onDragOver={(event) => entryDropTarget && handleDropTargetDragOver(event, entryDropTarget)}
onDragLeave={clearDropState}
onDrop={(event) => entryDropTarget && void handleDropOnTarget(event, entryDropTarget)}
onMouseDown={preventTextSelectionOnShift}
onClick={(event) => handleEntrySelection(entry, event)}
onDoubleClick={() => { if (!busy && activeSpace) openFolder(activeSpace.id, entry.path); }}
onContextMenu={(event) => openContextMenu(event, "folder", entry)}
onKeyDown={(event) => handleEntryKeyDown(entry, event)}
>
<div className="file-list-name-cell">
<div className="file-list-name">
<Folder className="file-row-icon" size={20} aria-hidden="true" />
<span><strong>{entry.name}</strong><small>{folderContentLabel(entry)}</small></span>
</div>
</div>
<span>{formatBytes(entry.totalSize)}</span>
<span className="file-row-tail"><span>{formatDate(entry.updatedAt)}</span></span>
</div>
) : (
<div
key={entry.id}
className={`file-list-row file-row ${isEntrySelected(entry) ? "is-selected" : ""}`}
role="row"
tabIndex={0}
draggable
onDragStart={(event) => handleInternalDragStart(entry, event)}
onDragEnd={() => { setInternalDrag(null); clearDropState(); }}
onMouseDown={preventTextSelectionOnShift}
onClick={(event) => handleEntrySelection(entry, event)}
onDoubleClick={() => { if (!busy) void downloadFile(settings, entry.file); }}
onContextMenu={(event) => openContextMenu(event, "file", entry)}
onKeyDown={(event) => handleEntryKeyDown(entry, event)}
>
<div className="file-list-name-cell">
<div className="file-list-name">
<File className="file-row-icon" size={20} aria-hidden="true" />
<span><strong>{searchActive ? entry.file.display_path : entry.file.filename}</strong></span>
</div>
</div>
<span>{formatBytes(entry.file.size_bytes)}</span>
<span className="file-row-tail"><span>{formatDate(entry.file.updated_at)}</span></span>
</div>
);
})}
{virtualExplorerRows.topSpacerHeight > 0 && (
<div className="file-list-virtual-spacer" style={{ height: virtualExplorerRows.topSpacerHeight }} aria-hidden="true" />
)}
{virtualExplorerRows.entries.map((entry, index) => renderExplorerEntry(entry, virtualExplorerRows.startIndex + index + 2))}
{virtualExplorerRows.bottomSpacerHeight > 0 && (
<div className="file-list-virtual-spacer" style={{ height: virtualExplorerRows.bottomSpacerHeight }} aria-hidden="true" />
)}
</div>
</div>
</section>
@@ -1378,34 +1504,15 @@ export default function FilesPage({ settings, auth }: { settings: ApiSettings; a
{dialog === "upload" && (
<FileDialog title={`Upload to ${activeDialogSpace?.label || "Files"} / ${activeDialogTarget?.folderPath || "Root"}`} onClose={closeDialog}>
<div
className={`file-upload-drop-zone ${dragActive ? "is-active" : ""}`}
role="button"
tabIndex={busy || !activeDialogSpace || !canUpload ? -1 : 0}
aria-label="Drop files here or click to select files"
aria-disabled={busy || !activeDialogSpace || !canUpload}
onClick={() => {
if (!busy && activeDialogSpace && canUpload) fileInputRef.current?.click();
}}
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>
<FileDropZone
disabled={busy || !activeDialogSpace || !canUpload}
busy={uploadActive}
progress={visibleUploadProgress}
busyLabel={uploadBusyLabel}
progressLabel={uploadProgressLabel}
note={`Files are uploaded into ${activeDialogTarget?.folderPath || "Root"}.`}
onFiles={(files) => handleFilesUpload(files)}
/>
<ToggleSwitch label="Unpack ZIP uploads" checked={unpackZip} onChange={setUnpackZip} disabled={busy} />
<div className="field-block">
<FieldLabel className="form-label" help="Choose the destination folder before selecting or dropping files.">Destination folder</FieldLabel>
@@ -1417,10 +1524,8 @@ export default function FilesPage({ settings, auth }: { settings: ApiSettings; a
onSelect={(folderPath) => activeDialogTarget && updateActiveDialogFolder(activeDialogTarget.spaceId, folderPath)}
/>
</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">
<Button onClick={closeDialog} disabled={busy}>Cancel</Button>
<Button variant="primary" onClick={() => fileInputRef.current?.click()} disabled={busy || !activeDialogSpace || !canUpload}>Select files</Button>
</div>
</FileDialog>
)}
@@ -1527,3 +1632,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(", ");
}

File diff suppressed because it is too large Load Diff

View File

@@ -2,6 +2,13 @@ import { formatDateTime as formatPlatformDateTime } from "@govoplan/core-webui";
import type { FileFolder, ManagedFile } from "../../../api/files";
import type { DragSelectionState, EntrySelectionKey, ExplorerEntry, FileEntry, FolderEntry, FolderNode, SortColumn, SortDirection } from "../types";
type FolderStats = {
directFiles: number;
childFolders: Set<string>;
totalSize: number;
updatedAt: string;
};
export function buildFolderTree(files: ManagedFile[], folders: FileFolder[]): FolderNode[] {
const byPath = new Map<string, FolderNode>();
const ensureNode = (path: string, persisted: boolean): FolderNode | null => {
@@ -71,21 +78,23 @@ export function buildExplorerEntries(files: ManagedFile[], folders: FileFolder[]
const prefix = folder ? `${folder}/` : "";
const folderMap = new Map<string, FolderEntry>();
const directFiles: FileEntry[] = [];
const folderStats = buildFolderStats(files, folders);
for (const persisted of folders) {
const path = normalizeFolder(persisted.path);
if (!path.startsWith(prefix) || path === folder) continue;
const relative = prefix ? path.slice(prefix.length) : path;
if (!relative || relative.includes("/")) continue;
const stats = folderStats.get(path);
folderMap.set(path, {
kind: "folder",
id: `folder:${path}`,
name: relative,
path,
fileCount: 0,
folderCount: 0,
totalSize: 0,
updatedAt: persisted.updated_at,
fileCount: stats?.directFiles ?? 0,
folderCount: stats?.childFolders.size ?? 0,
totalSize: stats?.totalSize ?? 0,
updatedAt: latestTimestamp(persisted.updated_at, stats?.updatedAt),
persisted: true
});
}
@@ -102,31 +111,22 @@ export function buildExplorerEntries(files: ManagedFile[], folders: FileFolder[]
}
const folderName = relativePath.slice(0, slashIndex);
const folderPath = prefix ? `${folder}/${folderName}` : folderName;
const existing = folderMap.get(folderPath);
if (existing) {
existing.totalSize += file.size_bytes;
if (file.updated_at > existing.updatedAt) existing.updatedAt = file.updated_at;
} else {
if (!folderMap.has(folderPath)) {
const stats = folderStats.get(folderPath);
folderMap.set(folderPath, {
kind: "folder",
id: `folder:${folderPath}`,
name: folderName,
path: folderPath,
fileCount: 0,
folderCount: 0,
totalSize: file.size_bytes,
updatedAt: file.updated_at,
fileCount: stats?.directFiles ?? 0,
folderCount: stats?.childFolders.size ?? 0,
totalSize: stats?.totalSize ?? file.size_bytes,
updatedAt: stats?.updatedAt || file.updated_at,
persisted: false
});
}
}
for (const entry of folderMap.values()) {
const counts = directFolderCounts(files, folders, entry.path);
entry.fileCount = counts.files;
entry.folderCount = counts.folders;
}
return [...Array.from(folderMap.values()), ...directFiles];
}
@@ -164,25 +164,55 @@ export function entryModifiedTime(entry: ExplorerEntry): number {
}
export function directFolderCounts(files: ManagedFile[], folders: FileFolder[], folderPath: string): { files: number; folders: number } {
const normalized = normalizeFolder(folderPath);
const prefix = normalized ? `${normalized}/` : "";
const directFiles = files.filter((file) => parentFolderPath(file.display_path) === normalized).length;
const childFolders = new Set<string>();
const stats = buildFolderStats(files, folders).get(normalizeFolder(folderPath));
return { files: stats?.directFiles ?? 0, folders: stats?.childFolders.size ?? 0 };
}
function buildFolderStats(files: ManagedFile[], folders: FileFolder[]): Map<string, FolderStats> {
const statsByPath = new Map<string, FolderStats>();
const ensureStats = (path: string): FolderStats => {
const normalized = normalizeFolder(path);
const existing = statsByPath.get(normalized);
if (existing) return existing;
const stats: FolderStats = { directFiles: 0, childFolders: new Set(), totalSize: 0, updatedAt: "" };
statsByPath.set(normalized, stats);
return stats;
};
for (const folder of folders) {
const path = normalizeFolder(folder.path);
if (!path.startsWith(prefix) || path === normalized) continue;
const relative = prefix ? path.slice(prefix.length) : path;
if (!relative) continue;
childFolders.add(relative.split("/")[0]);
if (!path) continue;
const parts = path.split("/");
const parentPath = normalizeFolder(parts.slice(0, -1).join("/"));
const name = parts[parts.length - 1];
if (name) ensureStats(parentPath).childFolders.add(name);
ensureStats(path);
}
for (const file of files) {
const path = normalizeFilePath(file.display_path);
if (!path.startsWith(prefix)) continue;
const relative = prefix ? path.slice(prefix.length) : path;
if (!relative || !relative.includes("/")) continue;
childFolders.add(relative.split("/")[0]);
const parts = normalizeFilePath(file.display_path || file.filename).split("/").filter(Boolean);
if (parts.length === 0) continue;
const directParentPath = normalizeFolder(parts.slice(0, -1).join("/"));
ensureStats(directParentPath).directFiles += 1;
for (let index = 0; index < parts.length - 1; index += 1) {
const folderPath = parts.slice(0, index + 1).join("/");
const stats = ensureStats(folderPath);
stats.totalSize += file.size_bytes;
stats.updatedAt = latestTimestamp(stats.updatedAt, file.updated_at);
const parentPath = normalizeFolder(parts.slice(0, index).join("/"));
ensureStats(parentPath).childFolders.add(parts[index]);
}
}
return { files: directFiles, folders: childFolders.size };
return statsByPath;
}
function latestTimestamp(current: string, candidate?: string): string {
if (!candidate) return current;
if (!current) return candidate;
return candidate > current ? candidate : current;
}
export function folderContentLabel(entry: FolderEntry): string {
@@ -209,13 +239,14 @@ export function buildFolderEntryFromSources(files: ManagedFile[], folders: FileF
const sortedDates = childFiles.map((file) => file.updated_at).sort();
const latestFileDate = sortedDates.length > 0 ? sortedDates[sortedDates.length - 1] : undefined;
const updatedAt = latestFileDate || persistedFolder?.updated_at || new Date().toISOString();
const counts = directFolderCounts(files, folders, normalizedPath);
return {
kind: "folder",
id: `folder:${normalizedPath}`,
name: lastPathSegment(normalizedPath) || "Root",
path: normalizedPath,
fileCount: directFolderCounts(files, folders, normalizedPath).files,
folderCount: directFolderCounts(files, folders, normalizedPath).folders,
fileCount: counts.files,
folderCount: counts.folders,
totalSize: childFiles.reduce((total, file) => total + file.size_bytes, 0),
updatedAt,
persisted: Boolean(persistedFolder)

View File

@@ -5,6 +5,8 @@ export { default as FilesPage } from "./features/files/FilesPage";
export * from "./api/files";
export type { PlatformWebModule, PlatformNavItem, PlatformRouteContribution, PlatformRouteContext } from "@govoplan/core-webui";
export { FolderTree } from "./features/files/components/FileManagerComponents";
export { default as ManagedFileChooser } from "./features/files/components/ManagedFileChooser";
export type { ManagedAttachmentSelection, ManagedFolderSelection } from "./features/files/components/ManagedFileChooser";
export { useFileTreeState } from "./features/files/hooks/useFileTreeState";
export type { FolderNode, SortColumn, SortDirection } from "./features/files/types";
export { buildExplorerEntries, buildFolderEntryFromSources, buildFolderTree, candidateRenamedPath, directFolderCounts, entryModifiedTime, entryName, entrySelectionKey, entrySize, fileIdsForSelection, folderAncestorPaths, folderBreadcrumbs, folderContentLabel, formatBytes, formatDate, isFileInFolder, isPathUnderOrSame, joinFolder, lastPathSegment, normalizeFilePath, normalizeFolder, parentFolderPath, parseDragState, sortExplorerEntries, sortFolderNodes, treeNodeKey } from "./features/files/utils/fileManagerUtils";

View File

@@ -1,5 +1,9 @@
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";
import ManagedFileChooser from "./features/files/components/ManagedFileChooser";
import { listFileSpaces, listFiles, listFolders, resolveFilePatterns, shareFilesWithTarget } from "./api/files";
const FilesPage = lazy(() => import("./features/files/FilesPage"));
const fileRead = ["files:file:read"];
@@ -12,7 +16,18 @@ export const filesModule: PlatformWebModule = {
navItems: [{ to: "/files", label: "Files", iconName: "folder", anyOf: fileRead, order: 40 }],
routes: [
{ path: "/files", anyOf: fileRead, order: 40, render: ({ settings, auth }) => createElement(FilesPage, { settings, auth }) }
]
],
uiCapabilities: {
"files.fileExplorer": {
FolderTree,
ManagedFileChooser,
listFileSpaces,
listFiles,
listFolders,
resolveFilePatterns,
shareFilesWithTarget
} satisfies FilesFileExplorerUiCapability
}
};
export default filesModule;

View File

@@ -356,6 +356,16 @@
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 {
color: var(--muted);
flex: 0 0 auto;
@@ -381,6 +391,11 @@
text-align: center;
}
.file-list-virtual-spacer {
min-height: 0;
pointer-events: none;
}
.file-context-menu {
position: fixed;
z-index: 110;
@@ -473,37 +488,6 @@
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 {
color: var(--danger-text);
font-weight: 700;
@@ -719,3 +703,467 @@
color: var(--text-strong);
outline: none;
}
/* Managed file chooser exposed through the files.fileExplorer capability. */
.managed-file-chooser-dialog {
display: grid;
grid-template-rows: auto minmax(0, 1fr) auto;
width: min(1080px, calc(100vw - 40px));
height: min(820px, calc(100vh - 40px));
max-height: min(820px, calc(100vh - 40px));
overflow: hidden;
}
.managed-file-chooser-dialog > .dialog-header {
padding: 16px 18px;
border-bottom: 1px solid var(--line);
background: var(--panel);
}
.managed-file-chooser-body {
display: flex;
flex-direction: column;
gap: 14px;
min-height: 0;
overflow: hidden;
padding: 0;
}
.managed-file-chooser-body > .alert {
margin: 14px 14px 0;
}
.managed-file-chooser-footer {
flex: 0 0 auto;
padding: 12px 18px;
border-top: 1px solid var(--line);
background: var(--panel);
box-shadow: 0 -8px 24px rgba(15, 23, 42, .06);
}
.managed-file-chooser-layout {
display: grid;
grid-template-columns: minmax(190px, 240px) minmax(0, 1fr);
flex: 1 1 auto;
min-height: 0;
max-height: none;
border: 0;
border-radius: 0;
overflow: hidden;
background: var(--panel);
}
.managed-file-chooser-spaces {
min-width: 0;
padding: 16px;
border-right: 1px solid var(--line);
background: var(--panel-soft);
overflow: auto;
}
.managed-file-chooser-spaces.file-tree-panel {
display: flex;
padding: 0;
overflow: hidden;
}
.managed-file-chooser-spaces .file-tree-list {
display: flex;
flex-direction: column;
min-height: 0;
padding-bottom: 12px;
}
.managed-file-chooser-spaces .file-tree-space.is-active {
display: flex;
flex: 1 1 auto;
flex-direction: column;
min-height: 0;
}
.managed-file-chooser-spaces h3 {
margin: 0 0 12px;
font-size: 13px;
text-transform: uppercase;
letter-spacing: .04em;
color: var(--muted);
}
.managed-file-space-list {
display: grid;
gap: 7px;
}
.managed-file-space-button,
.managed-file-entry {
width: 100%;
border: 1px solid transparent;
border-radius: 9px;
background: transparent;
color: var(--ink);
text-align: left;
cursor: pointer;
}
.managed-file-space-button {
display: grid;
grid-template-columns: 20px minmax(0, 1fr);
gap: 9px;
align-items: start;
padding: 9px;
}
.managed-file-space-button span,
.managed-file-entry > span:not(.managed-file-shared-badge) {
display: grid;
gap: 2px;
min-width: 0;
}
.managed-file-space-button small,
.managed-file-entry small {
color: var(--muted);
font-size: 11px;
}
.managed-file-space-button:hover:not(:disabled),
.managed-file-space-button.is-selected {
border-color: var(--line-dark);
background: var(--panel);
}
.managed-file-space-button.is-selected {
border-color: var(--accent);
box-shadow: inset 3px 0 0 var(--accent);
}
.managed-file-space-button:disabled {
cursor: not-allowed;
opacity: .45;
}
.managed-file-chooser-browser {
display: grid;
grid-template-rows: auto auto minmax(0, 1fr) auto;
min-width: 0;
min-height: 0;
}
.managed-file-chooser-browser.folder-mode {
grid-template-rows: auto minmax(0, 1fr) auto;
}
.managed-file-chooser-toolbar {
display: flex;
justify-content: space-between;
gap: 12px;
align-items: center;
padding: 12px 14px;
border-bottom: 1px solid var(--line);
}
.managed-file-breadcrumb {
display: flex;
flex-wrap: wrap;
gap: 5px;
align-items: center;
min-width: 0;
}
.managed-file-breadcrumb > button,
.managed-file-breadcrumb span button {
display: inline-flex;
gap: 5px;
align-items: center;
border: 0;
border-radius: 6px;
background: transparent;
color: var(--ink);
padding: 5px 6px;
cursor: pointer;
}
.managed-file-breadcrumb button:hover:not(:disabled) {
background: var(--panel-soft);
}
.managed-pattern-editor {
display: grid;
gap: 8px;
padding: 12px 14px;
border-bottom: 1px solid var(--line);
background: var(--panel-soft);
}
.managed-pattern-editor label {
display: grid;
gap: 6px;
font-size: 12px;
font-weight: 700;
}
.managed-file-entry-table {
display: grid;
grid-template-rows: auto minmax(0, 1fr);
min-height: 0;
overflow: hidden;
}
.managed-file-entry-head,
.managed-file-entry {
grid-template-columns: 22px minmax(0, 1fr) 110px 160px;
}
.managed-file-entry-head {
display: grid;
gap: 9px;
align-items: center;
min-height: 38px;
padding: 0 20px;
border-bottom: 1px solid var(--line);
background: var(--panel-soft);
color: var(--muted);
font-size: 12px;
font-weight: 750;
}
.managed-file-entry-head button {
display: inline-flex;
align-items: center;
justify-content: flex-start;
gap: 5px;
width: max-content;
max-width: 100%;
border: 0;
background: transparent;
color: inherit;
padding: 5px 0;
font: inherit;
cursor: pointer;
}
.managed-file-entry-head button.is-sorted {
color: var(--text-strong);
}
.managed-file-entry-list {
display: block;
padding: 10px;
min-height: 0;
overflow: auto;
}
.managed-file-entry {
display: grid;
gap: 9px;
align-items: center;
min-height: 52px;
padding: 8px 10px;
margin: 0 0 4px;
}
.managed-file-entry:last-child {
margin-bottom: 0;
}
.managed-file-entry:hover:not(:disabled) {
border-color: var(--line);
background: var(--panel-soft);
}
.managed-file-entry.is-selected {
border-color: var(--accent);
background: var(--accent-soft);
}
.managed-file-entry:disabled {
color: var(--ink);
opacity: 1;
cursor: default;
}
.managed-file-entry.is-folder:not(:disabled) {
cursor: pointer;
}
.managed-file-entry.is-context-only {
opacity: .56;
}
.managed-file-entry.is-parent:disabled {
opacity: .38;
}
.managed-file-entry-name {
display: grid;
gap: 2px;
min-width: 0;
}
.managed-file-entry-name strong,
.managed-file-entry-name small {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.managed-file-entry-name small {
display: inline-flex;
align-items: center;
gap: 4px;
}
.managed-file-entry-size,
.managed-file-entry-modified {
color: var(--muted);
font-size: 12px;
white-space: nowrap;
}
.managed-file-shared-badge {
display: inline-flex;
gap: 4px;
align-items: center;
border: 1px solid var(--success-line, var(--line));
border-radius: 999px;
padding: 3px 7px;
color: var(--success, var(--muted));
font-size: 11px;
white-space: nowrap;
}
.managed-file-empty {
padding: 28px 16px;
text-align: center;
}
.managed-file-virtual-spacer {
min-height: 0;
pointer-events: none;
}
.managed-file-tree-virtual-list {
flex: 1 1 auto;
min-height: 80px;
overflow: auto;
}
.managed-file-chooser-note {
margin: 0;
padding: 10px 14px;
border-top: 1px solid var(--line);
background: var(--panel-soft);
}
.managed-pattern-summary {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
color: var(--muted);
font-size: 12px;
font-weight: 600;
}
.managed-pattern-results {
display: grid;
grid-template-rows: auto minmax(0, 1fr);
min-width: 0;
min-height: 0;
overflow: hidden;
}
.managed-pattern-results .file-list-table {
min-width: 680px;
min-height: 0;
overflow: auto;
}
.managed-pattern-result-row {
width: 100%;
border-top: 0;
border-right: 0;
border-left: 0;
background: transparent;
color: var(--ink);
text-align: left;
font: inherit;
cursor: pointer;
}
.managed-pattern-result-row .file-list-name > span {
display: grid;
min-width: 0;
}
.managed-pattern-result-row .file-list-name strong {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.managed-pattern-result-row .file-list-name small {
color: var(--muted);
font-size: 11px;
}
.managed-pattern-rendered {
display: block;
color: var(--muted);
}
.split-field-action {
gap: 0;
}
.split-field-action > input,
.split-field-action > select,
.split-field-action > textarea {
border-top-right-radius: 0 !important;
border-bottom-right-radius: 0 !important;
}
.split-field-action > button,
.split-field-action > .button,
.split-field-action > .btn {
align-self: stretch;
margin-left: -1px;
border-top-left-radius: 0;
border-bottom-left-radius: 0;
box-shadow: none;
}
@media (max-width: 850px) {
.managed-file-entry-head,
.managed-file-entry {
grid-template-columns: 22px minmax(0, 1fr) 100px;
}
.managed-file-entry-head > :last-child,
.managed-file-entry-modified {
display: none;
}
}
@media (max-width: 760px) {
.managed-file-chooser-dialog {
width: calc(100vw - 20px);
height: calc(100vh - 20px);
}
.managed-file-chooser-layout {
grid-template-columns: 1fr;
max-height: calc(100vh - 220px);
}
.managed-file-chooser-spaces {
border-right: 0;
border-bottom: 1px solid var(--line);
max-height: 160px;
}
.managed-file-chooser-toolbar {
align-items: flex-start;
flex-direction: column;
}
}