feat: attachments on tickets and comments
Files are uploaded over REST, stored on disk (a volume in Docker) and recorded on the ticket as events; the bytes are written first, so no attachment ever points at a missing file. Only images, video, audio, PDF and plain text are shown inline, everything with nosniff and a sandbox CSP. The web shows thumbnails, uploads by drag and drop or by pasting a screenshot, and attaches files to new comments. Also adds `nx run api:contracts`, which writes schema.gql and openapi.json without starting the API or any database. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
|
||||
import { BusinessRuleError } from '@task-stream/api/shared/domain';
|
||||
import { AttachmentStorage, attachmentKey } from '../ports/attachment-storage';
|
||||
import { AttachFileCommand } from './attach-file.command';
|
||||
import { CommandResult, ack } from './command-result';
|
||||
import { WriteAccess } from './write-access';
|
||||
|
||||
/**
|
||||
* Stores the bytes first and records them on the ticket after: a file with no
|
||||
* record is cleaned up here, never a record with no file.
|
||||
*/
|
||||
@CommandHandler(AttachFileCommand)
|
||||
export class AttachFileCommandHandler
|
||||
implements ICommandHandler<AttachFileCommand>
|
||||
{
|
||||
constructor(
|
||||
private readonly access: WriteAccess,
|
||||
private readonly storage: AttachmentStorage,
|
||||
) {}
|
||||
|
||||
async execute(command: AttachFileCommand): Promise<CommandResult> {
|
||||
const { issue } = await this.access.issueForContributor(
|
||||
command.issueId,
|
||||
command.actorId,
|
||||
);
|
||||
if (command.commentId) {
|
||||
const comment = await this.access.comment(command.commentId);
|
||||
if (comment.issueId !== issue.id) {
|
||||
throw new BusinessRuleError(
|
||||
`That comment belongs to another ticket, not ${issue.key}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const id = randomUUID();
|
||||
const key = attachmentKey(issue.projectId, issue.id, id);
|
||||
issue.attach(command.actorId, {
|
||||
id,
|
||||
fileName: command.file.fileName,
|
||||
mimeType: command.file.mimeType,
|
||||
size: command.file.content.length,
|
||||
uploadedBy: command.actorId,
|
||||
uploadedAt: new Date().toISOString(),
|
||||
commentId: command.commentId,
|
||||
});
|
||||
|
||||
await this.storage.put(key, command.file.content);
|
||||
try {
|
||||
await issue.commitAndWait();
|
||||
} catch (error) {
|
||||
await this.storage.remove(key);
|
||||
throw error;
|
||||
}
|
||||
return ack(issue);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Command } from '@nestjs/cqrs';
|
||||
import { CommandResult } from './command-result';
|
||||
|
||||
export interface IncomingFile {
|
||||
fileName: string;
|
||||
mimeType: string;
|
||||
content: Buffer;
|
||||
}
|
||||
|
||||
export class AttachFileCommand extends Command<CommandResult> {
|
||||
constructor(
|
||||
public readonly actorId: string,
|
||||
public readonly issueId: string,
|
||||
public readonly file: IncomingFile,
|
||||
/** Places it under one of the ticket's comments. */
|
||||
public readonly commentId: string | null = null,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,8 @@ import { PurgeCommentCommandHandler } from './purge-comment.command-handler';
|
||||
import { DropLinksToIssueCommandHandler } from './drop-links-to-issue.command-handler';
|
||||
import { DetachIssueFromReleaseCommandHandler } from './detach-issue-from-release.command-handler';
|
||||
import { UnassignIssueCommandHandler } from './unassign-issue.command-handler';
|
||||
import { AttachFileCommandHandler } from './attach-file.command-handler';
|
||||
import { DetachFileCommandHandler } from './detach-file.command-handler';
|
||||
|
||||
export const COMMAND_HANDLERS = [
|
||||
CreateProjectCommandHandler,
|
||||
@@ -55,4 +57,6 @@ export const COMMAND_HANDLERS = [
|
||||
DropLinksToIssueCommandHandler,
|
||||
DetachIssueFromReleaseCommandHandler,
|
||||
UnassignIssueCommandHandler,
|
||||
AttachFileCommandHandler,
|
||||
DetachFileCommandHandler,
|
||||
];
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
} from '@task-stream/api/shared/domain';
|
||||
import {
|
||||
Comment,
|
||||
Issue,
|
||||
IssueStatus,
|
||||
Project,
|
||||
IssueType,
|
||||
@@ -20,6 +21,7 @@ import {
|
||||
} from '@task-stream/api/tracker/domain';
|
||||
import {
|
||||
FakeUserDirectory,
|
||||
InMemoryAttachmentStorage,
|
||||
InMemoryEventStore,
|
||||
InMemoryEventStorePublisher,
|
||||
InMemoryIssueNumbers,
|
||||
@@ -32,9 +34,12 @@ import { IssueNumbersRepository } from '../ports/issue-numbers.repository';
|
||||
import { ProjectKeysRepository } from '../ports/project-keys.repository';
|
||||
import { ReleaseNamesRepository } from '../ports/release-names.repository';
|
||||
import { UserDirectory } from '../ports/user-directory';
|
||||
import { AttachmentStorage } from '../ports/attachment-storage';
|
||||
import { AddCommentCommand } from './add-comment.command';
|
||||
import { AddProjectMemberCommand } from './add-project-member.command';
|
||||
import { AssignIssueCommand } from './assign-issue.command';
|
||||
import { AttachFileCommand } from './attach-file.command';
|
||||
import { DetachFileCommand } from './detach-file.command';
|
||||
import { ChangeIssueStatusCommand } from './change-issue-status.command';
|
||||
import { COMMAND_HANDLERS } from './command-handlers';
|
||||
import { CommandResult } from './command-result';
|
||||
@@ -48,6 +53,7 @@ import { WriteAccess } from './write-access';
|
||||
|
||||
async function setup() {
|
||||
const store = new InMemoryEventStore();
|
||||
const files = new InMemoryAttachmentStorage();
|
||||
const users = new FakeUserDirectory()
|
||||
.add('owner')
|
||||
.add('dev')
|
||||
@@ -62,6 +68,7 @@ async function setup() {
|
||||
WriteAccess,
|
||||
AggregateRehydrator,
|
||||
{ provide: EventStore, useValue: store },
|
||||
{ provide: AttachmentStorage, useValue: files },
|
||||
{ provide: UserDirectory, useValue: users },
|
||||
{ provide: ProjectKeysRepository, useClass: InMemoryProjectKeys },
|
||||
{ provide: IssueNumbersRepository, useClass: InMemoryIssueNumbers },
|
||||
@@ -78,7 +85,12 @@ async function setup() {
|
||||
const commandBus = moduleRef.get(CommandBus);
|
||||
const run = (command: object): Promise<CommandResult> =>
|
||||
commandBus.execute(command as never);
|
||||
return { store, run, rehydrator: moduleRef.get(AggregateRehydrator) };
|
||||
return {
|
||||
store,
|
||||
files,
|
||||
run,
|
||||
rehydrator: moduleRef.get(AggregateRehydrator),
|
||||
};
|
||||
}
|
||||
|
||||
async function projectWithTeam(run: (c: object) => Promise<CommandResult>) {
|
||||
@@ -178,6 +190,74 @@ describe('tracker commands (event sourced)', () => {
|
||||
).rejects.toThrow(BusinessRuleError);
|
||||
});
|
||||
|
||||
describe('attachments', () => {
|
||||
const png = {
|
||||
fileName: 'captura.png',
|
||||
mimeType: 'image/png',
|
||||
content: Buffer.from('fake png'),
|
||||
};
|
||||
|
||||
it('stores the file and records it on the ticket', async () => {
|
||||
const { run, files, rehydrator } = await setup();
|
||||
const projectId = await projectWithTeam(run);
|
||||
const issue = await run(
|
||||
new CreateIssueCommand('qa', projectId, IssueType.BUG, 'Crash', {}),
|
||||
);
|
||||
|
||||
await run(new AttachFileCommand('qa', issue.id, png));
|
||||
|
||||
const rebuilt = await rehydrator.rehydrate(issue.id, Issue);
|
||||
expect(rebuilt.attachments).toHaveLength(1);
|
||||
expect(rebuilt.attachments[0]).toMatchObject({
|
||||
fileName: 'captura.png',
|
||||
size: 8,
|
||||
uploadedBy: 'qa',
|
||||
});
|
||||
expect([...files.files.keys()]).toEqual([
|
||||
`${projectId}/${issue.id}/${rebuilt.attachments[0].id}`,
|
||||
]);
|
||||
});
|
||||
|
||||
it('keeps no file when the ticket cannot take it', async () => {
|
||||
const { run, files } = await setup();
|
||||
const projectId = await projectWithTeam(run);
|
||||
const issue = await run(
|
||||
new CreateIssueCommand('qa', projectId, IssueType.BUG, 'Crash', {}),
|
||||
);
|
||||
|
||||
await expect(
|
||||
run(new AttachFileCommand('pm', issue.id, png)),
|
||||
).rejects.toThrow(ForbiddenError);
|
||||
await expect(
|
||||
run(
|
||||
new AttachFileCommand('qa', issue.id, {
|
||||
...png,
|
||||
content: Buffer.alloc(0),
|
||||
}),
|
||||
),
|
||||
).rejects.toThrow();
|
||||
expect(files.files.size).toBe(0);
|
||||
});
|
||||
|
||||
it('lets the uploader or an admin remove it, and deletes the bytes', async () => {
|
||||
const { run, files, rehydrator } = await setup();
|
||||
const projectId = await projectWithTeam(run);
|
||||
const issue = await run(
|
||||
new CreateIssueCommand('qa', projectId, IssueType.BUG, 'Crash', {}),
|
||||
);
|
||||
await run(new AttachFileCommand('qa', issue.id, png));
|
||||
const [attachment] = (await rehydrator.rehydrate(issue.id, Issue))
|
||||
.attachments;
|
||||
|
||||
await expect(
|
||||
run(new DetachFileCommand('dev', issue.id, attachment.id)),
|
||||
).rejects.toThrow(ForbiddenError);
|
||||
await run(new DetachFileCommand('owner', issue.id, attachment.id));
|
||||
|
||||
expect(files.files.size).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
it('does not let viewers modify tickets', async () => {
|
||||
const { run } = await setup();
|
||||
const projectId = await projectWithTeam(run);
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
|
||||
import { ProjectRole } from '@task-stream/api/tracker/domain';
|
||||
import { AttachmentStorage, attachmentKey } from '../ports/attachment-storage';
|
||||
import { CommandResult, ack } from './command-result';
|
||||
import { DetachFileCommand } from './detach-file.command';
|
||||
import { WriteAccess } from './write-access';
|
||||
|
||||
/** Removes the record first; the bytes go once nothing points at them. */
|
||||
@CommandHandler(DetachFileCommand)
|
||||
export class DetachFileCommandHandler
|
||||
implements ICommandHandler<DetachFileCommand>
|
||||
{
|
||||
constructor(
|
||||
private readonly access: WriteAccess,
|
||||
private readonly storage: AttachmentStorage,
|
||||
) {}
|
||||
|
||||
async execute(command: DetachFileCommand): Promise<CommandResult> {
|
||||
const { issue, project } = await this.access.issueForContributor(
|
||||
command.issueId,
|
||||
command.actorId,
|
||||
);
|
||||
const role = project.roleOf(command.actorId);
|
||||
issue.detach(
|
||||
command.actorId,
|
||||
command.attachmentId,
|
||||
role === ProjectRole.OWNER || role === ProjectRole.ADMIN,
|
||||
);
|
||||
await issue.commitAndWait();
|
||||
await this.storage.remove(
|
||||
attachmentKey(issue.projectId, issue.id, command.attachmentId),
|
||||
);
|
||||
return ack(issue);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Command } from '@nestjs/cqrs';
|
||||
import { CommandResult } from './command-result';
|
||||
|
||||
export class DetachFileCommand extends Command<CommandResult> {
|
||||
constructor(
|
||||
public readonly actorId: string,
|
||||
public readonly issueId: string,
|
||||
public readonly attachmentId: string,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
}
|
||||
@@ -26,3 +26,5 @@ export * from './purge-comment.command';
|
||||
export * from './drop-links-to-issue.command';
|
||||
export * from './detach-issue-from-release.command';
|
||||
export * from './unassign-issue.command';
|
||||
export * from './attach-file.command';
|
||||
export * from './detach-file.command';
|
||||
|
||||
@@ -3,6 +3,8 @@ import {
|
||||
CommentDeletedEvent,
|
||||
CommentEditedEvent,
|
||||
IssueAssignedEvent,
|
||||
IssueAttachmentAddedEvent,
|
||||
IssueAttachmentRemovedEvent,
|
||||
IssueCreatedEvent,
|
||||
IssueLinkedEvent,
|
||||
IssueLinkType,
|
||||
@@ -135,6 +137,11 @@ export function describeEvent(
|
||||
: `${actor} sacó ${issueKey} de su release`;
|
||||
}
|
||||
|
||||
if (event instanceof IssueAttachmentAddedEvent)
|
||||
return `${actor} adjuntó ${event.attachment.fileName} a ${issueKey}`;
|
||||
if (event instanceof IssueAttachmentRemovedEvent)
|
||||
return `${actor} quitó el adjunto ${event.fileName} de ${issueKey}`;
|
||||
|
||||
if (event instanceof CommentAddedEvent)
|
||||
return `${actor} comentó en ${issueKey}`;
|
||||
if (event instanceof CommentEditedEvent)
|
||||
|
||||
@@ -5,6 +5,8 @@ import {
|
||||
CommentDeletedEvent,
|
||||
CommentEditedEvent,
|
||||
IssueAssignedEvent,
|
||||
IssueAttachmentAddedEvent,
|
||||
IssueAttachmentRemovedEvent,
|
||||
IssueCreatedEvent,
|
||||
IssueLinkedEvent,
|
||||
IssueReleaseChangedEvent,
|
||||
@@ -51,6 +53,8 @@ import { versionOf } from './read-model-notifier';
|
||||
IssueLinkedEvent,
|
||||
IssueUnlinkedEvent,
|
||||
IssueReleaseChangedEvent,
|
||||
IssueAttachmentAddedEvent,
|
||||
IssueAttachmentRemovedEvent,
|
||||
CommentAddedEvent,
|
||||
CommentEditedEvent,
|
||||
CommentDeletedEvent,
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { EventsHandler, IEventHandler } from '@nestjs/cqrs';
|
||||
import { IssueDeletedEvent } from '@task-stream/api/tracker/domain';
|
||||
import {
|
||||
AttachmentStorage,
|
||||
issueAttachmentsPrefix,
|
||||
} from '../ports/attachment-storage';
|
||||
|
||||
/** A deleted ticket takes its files with it. */
|
||||
@EventsHandler(IssueDeletedEvent)
|
||||
export class AttachmentCleanupEventHandler
|
||||
implements IEventHandler<IssueDeletedEvent>
|
||||
{
|
||||
constructor(private readonly storage: AttachmentStorage) {}
|
||||
|
||||
async handle(event: IssueDeletedEvent) {
|
||||
await this.storage.removePrefix(
|
||||
issueAttachmentsPrefix(event.projectId, event.aggregateId),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,9 @@ import { ProjectSettingsChangedEventHandler } from './project-settings-changed.e
|
||||
import { ProjectDeletedEventHandler } from './project-deleted.event-handler';
|
||||
import { IssueDeletedEventHandler } from './issue-deleted.event-handler';
|
||||
import { ReleaseDeletedEventHandler } from './release-deleted.event-handler';
|
||||
import { IssueAttachmentAddedEventHandler } from './issue-attachment-added.event-handler';
|
||||
import { IssueAttachmentRemovedEventHandler } from './issue-attachment-removed.event-handler';
|
||||
import { AttachmentCleanupEventHandler } from './attachment-cleanup.event-handler';
|
||||
|
||||
/** Read-model projections (MongoDB) + realtime, fed by the EventsBridge. */
|
||||
export const EVENT_HANDLERS = [
|
||||
@@ -52,6 +55,9 @@ export const EVENT_HANDLERS = [
|
||||
ReleaseCreatedEventHandler,
|
||||
ReleaseShippedEventHandler,
|
||||
ReleaseUpdatedEventHandler,
|
||||
IssueAttachmentAddedEventHandler,
|
||||
IssueAttachmentRemovedEventHandler,
|
||||
AttachmentCleanupEventHandler,
|
||||
];
|
||||
|
||||
export { ReadModelNotifier };
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { EventsHandler, IEventHandler } from '@nestjs/cqrs';
|
||||
import { IssueAttachmentAddedEvent } from '@task-stream/api/tracker/domain';
|
||||
import { UpsertMaterializedIssueRepository } from '../ports/upsert-materialized-issue.repository';
|
||||
import { UserDirectory } from '../ports/user-directory';
|
||||
import { ReadModelNotifier, versionOf } from './read-model-notifier';
|
||||
|
||||
@EventsHandler(IssueAttachmentAddedEvent)
|
||||
export class IssueAttachmentAddedEventHandler
|
||||
implements IEventHandler<IssueAttachmentAddedEvent>
|
||||
{
|
||||
constructor(
|
||||
private readonly upsertMaterializedIssueRepository: UpsertMaterializedIssueRepository,
|
||||
private readonly users: UserDirectory,
|
||||
private readonly notifier: ReadModelNotifier,
|
||||
) {}
|
||||
|
||||
async handle(event: IssueAttachmentAddedEvent) {
|
||||
const { attachment } = event;
|
||||
const users = await this.users.refs([attachment.uploadedBy]);
|
||||
await this.upsertMaterializedIssueRepository.upsert({
|
||||
id: event.aggregateId,
|
||||
updatedAt: event.occurredAt,
|
||||
version: versionOf(event),
|
||||
});
|
||||
await this.upsertMaterializedIssueRepository.addAttachment(
|
||||
event.aggregateId,
|
||||
{ ...attachment, uploadedBy: users.of(attachment.uploadedBy) },
|
||||
);
|
||||
await this.notifier.issue(event.aggregateId, event);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { EventsHandler, IEventHandler } from '@nestjs/cqrs';
|
||||
import { IssueAttachmentRemovedEvent } from '@task-stream/api/tracker/domain';
|
||||
import { UpsertMaterializedIssueRepository } from '../ports/upsert-materialized-issue.repository';
|
||||
import { ReadModelNotifier, versionOf } from './read-model-notifier';
|
||||
|
||||
@EventsHandler(IssueAttachmentRemovedEvent)
|
||||
export class IssueAttachmentRemovedEventHandler
|
||||
implements IEventHandler<IssueAttachmentRemovedEvent>
|
||||
{
|
||||
constructor(
|
||||
private readonly upsertMaterializedIssueRepository: UpsertMaterializedIssueRepository,
|
||||
private readonly notifier: ReadModelNotifier,
|
||||
) {}
|
||||
|
||||
async handle(event: IssueAttachmentRemovedEvent) {
|
||||
await this.upsertMaterializedIssueRepository.upsert({
|
||||
id: event.aggregateId,
|
||||
updatedAt: event.occurredAt,
|
||||
version: versionOf(event),
|
||||
});
|
||||
await this.upsertMaterializedIssueRepository.removeAttachment(
|
||||
event.aggregateId,
|
||||
event.attachmentId,
|
||||
);
|
||||
await this.notifier.issue(event.aggregateId, event);
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,11 @@ import {
|
||||
IssueReadModel,
|
||||
} from '@task-stream/api/tracker/domain';
|
||||
import { AssignIssueCommand } from './commands/assign-issue.command';
|
||||
import {
|
||||
AttachFileCommand,
|
||||
IncomingFile,
|
||||
} from './commands/attach-file.command';
|
||||
import { DetachFileCommand } from './commands/detach-file.command';
|
||||
import { ChangeIssueStatusCommand } from './commands/change-issue-status.command';
|
||||
import { CommandResult } from './commands/command-result';
|
||||
import { CreateIssueCommand } from './commands/create-issue.command';
|
||||
@@ -16,6 +21,10 @@ import { UnlinkIssuesCommand } from './commands/unlink-issues.command';
|
||||
import { UpdateIssueCommand } from './commands/update-issue.command';
|
||||
import { IssueFilter, Page } from './ports/find-issues.repository';
|
||||
import { GetActivityQuery } from './queries/get-activity.query';
|
||||
import {
|
||||
AttachmentDownload,
|
||||
GetAttachmentQuery,
|
||||
} from './queries/get-attachment.query';
|
||||
import { GetIssueQuery } from './queries/get-issue.query';
|
||||
import { GetIssuesByIdsQuery } from './queries/get-issues-by-ids.query';
|
||||
import { SearchIssuesQuery } from './queries/search-issues.query';
|
||||
@@ -126,6 +135,39 @@ export class IssuesService {
|
||||
);
|
||||
}
|
||||
|
||||
/** Attaches a file to the ticket, or to one of its comments. */
|
||||
attach(
|
||||
actorId: string,
|
||||
issueId: string,
|
||||
file: IncomingFile,
|
||||
commentId: string | null = null,
|
||||
): Promise<CommandResult> {
|
||||
return this.commandBus.execute(
|
||||
new AttachFileCommand(actorId, issueId, file, commentId),
|
||||
);
|
||||
}
|
||||
|
||||
detach(
|
||||
actorId: string,
|
||||
issueId: string,
|
||||
attachmentId: string,
|
||||
): Promise<CommandResult> {
|
||||
return this.commandBus.execute(
|
||||
new DetachFileCommand(actorId, issueId, attachmentId),
|
||||
);
|
||||
}
|
||||
|
||||
/** A ticket's file, with its bytes, for whoever can read the ticket. */
|
||||
download(
|
||||
viewerId: string | null,
|
||||
issueId: string,
|
||||
attachmentId: string,
|
||||
): Promise<AttachmentDownload> {
|
||||
return this.queryBus.execute(
|
||||
new GetAttachmentQuery(viewerId, issueId, attachmentId),
|
||||
);
|
||||
}
|
||||
|
||||
findOne(viewerId: string | null, idOrKey: string): Promise<IssueReadModel> {
|
||||
return this.queryBus.execute(new GetIssueQuery(viewerId, idOrKey));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { Readable } from 'node:stream';
|
||||
|
||||
/** Where the bytes of attached files live (the tickets only record them). */
|
||||
export abstract class AttachmentStorage {
|
||||
abstract put(key: string, content: Buffer): Promise<void>;
|
||||
/** Fails with NotFoundError when there is nothing at `key`. */
|
||||
abstract read(key: string): Promise<Readable>;
|
||||
/** Idempotent: removing what is not there is fine. */
|
||||
abstract remove(key: string): Promise<void>;
|
||||
/** Everything under `prefix` (a ticket's files, when it is deleted). */
|
||||
abstract removePrefix(prefix: string): Promise<void>;
|
||||
}
|
||||
|
||||
/** One folder per project and ticket, so a ticket's files go together. */
|
||||
export const attachmentKey = (
|
||||
projectId: string,
|
||||
issueId: string,
|
||||
attachmentId: string,
|
||||
): string => `${projectId}/${issueId}/${attachmentId}`;
|
||||
|
||||
export const issueAttachmentsPrefix = (
|
||||
projectId: string,
|
||||
issueId: string,
|
||||
): string => `${projectId}/${issueId}/`;
|
||||
@@ -17,3 +17,4 @@ export * from './release-issues.repository';
|
||||
export * from './upsert-materialized-timeline.repository';
|
||||
export * from './find-timeline.repository';
|
||||
export * from './tracker-streams.repository';
|
||||
export * from './attachment-storage';
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
AttachmentReadModel,
|
||||
IssueLinkReadModel,
|
||||
IssueReadModel,
|
||||
StatusCategory,
|
||||
@@ -8,7 +9,7 @@ export abstract class UpsertMaterializedIssueRepository {
|
||||
/** Applied only if `version` is newer than the stored one (idempotent). */
|
||||
abstract upsert(
|
||||
issue: Pick<IssueReadModel, 'id' | 'version'> &
|
||||
Partial<Omit<IssueReadModel, 'links' | 'commentCount'>>,
|
||||
Partial<Omit<IssueReadModel, 'links' | 'commentCount' | 'attachments'>>,
|
||||
): Promise<void>;
|
||||
/** Adds a relation to an issue (idempotent). */
|
||||
abstract addLink(issueId: string, link: IssueLinkReadModel): Promise<void>;
|
||||
@@ -16,6 +17,15 @@ export abstract class UpsertMaterializedIssueRepository {
|
||||
issueId: string,
|
||||
link: Omit<IssueLinkReadModel, 'issueKey'>,
|
||||
): Promise<void>;
|
||||
/** Adds a file to an issue (idempotent). */
|
||||
abstract addAttachment(
|
||||
issueId: string,
|
||||
attachment: AttachmentReadModel,
|
||||
): Promise<void>;
|
||||
abstract removeAttachment(
|
||||
issueId: string,
|
||||
attachmentId: string,
|
||||
): Promise<void>;
|
||||
abstract setCommentCount(
|
||||
issueId: string,
|
||||
commentCount: number,
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { IQueryHandler, QueryHandler } from '@nestjs/cqrs';
|
||||
import { NotFoundError } from '@task-stream/api/shared/domain';
|
||||
import { AttachmentStorage, attachmentKey } from '../ports/attachment-storage';
|
||||
import { FindIssuesRepository } from '../ports/find-issues.repository';
|
||||
import { AttachmentDownload, GetAttachmentQuery } from './get-attachment.query';
|
||||
import { ReadAccess } from './read-access';
|
||||
|
||||
@QueryHandler(GetAttachmentQuery)
|
||||
export class GetAttachmentQueryHandler
|
||||
implements IQueryHandler<GetAttachmentQuery, AttachmentDownload>
|
||||
{
|
||||
constructor(
|
||||
private readonly findIssues: FindIssuesRepository,
|
||||
private readonly storage: AttachmentStorage,
|
||||
private readonly access: ReadAccess,
|
||||
) {}
|
||||
|
||||
async execute(query: GetAttachmentQuery): Promise<AttachmentDownload> {
|
||||
const issue = this.access.assertFound(
|
||||
await this.findIssues.findById(query.issueId),
|
||||
'Attachment',
|
||||
query.attachmentId,
|
||||
);
|
||||
await this.access.assertCanView(issue.projectId, query.viewerId, {
|
||||
entity: 'Attachment',
|
||||
ref: query.attachmentId,
|
||||
});
|
||||
const attachment = (issue.attachments ?? []).find(
|
||||
(a) => a.id === query.attachmentId,
|
||||
);
|
||||
if (!attachment) throw new NotFoundError('Attachment', query.attachmentId);
|
||||
return {
|
||||
attachment,
|
||||
content: await this.storage.read(
|
||||
attachmentKey(issue.projectId, issue.id, attachment.id),
|
||||
),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Query } from '@nestjs/cqrs';
|
||||
import { AttachmentReadModel } from '@task-stream/api/tracker/domain';
|
||||
import type { Readable } from 'node:stream';
|
||||
|
||||
export interface AttachmentDownload {
|
||||
attachment: AttachmentReadModel;
|
||||
content: Readable;
|
||||
}
|
||||
|
||||
/** A ticket's file, for whoever can read the ticket. */
|
||||
export class GetAttachmentQuery extends Query<AttachmentDownload> {
|
||||
constructor(
|
||||
/** Null: anonymous (public projects only). */
|
||||
public readonly viewerId: string | null,
|
||||
public readonly issueId: string,
|
||||
public readonly attachmentId: string,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
}
|
||||
@@ -16,3 +16,4 @@ export * from './get-upcoming-releases.query';
|
||||
export * from './search-issues.query';
|
||||
export * from './search-my-issues.query';
|
||||
export * from './get-public-projects.query';
|
||||
export * from './get-attachment.query';
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { GetAttachmentQueryHandler } from './get-attachment.query-handler';
|
||||
import { GetPublicProjectsQueryHandler } from './get-public-projects.query-handler';
|
||||
import { CanViewProjectQueryHandler } from './can-view-project.query-handler';
|
||||
import { GetActivityQueryHandler } from './get-activity.query-handler';
|
||||
@@ -36,4 +37,5 @@ export const QUERY_HANDLERS = [
|
||||
GetUpcomingReleasesQueryHandler,
|
||||
SearchIssuesQueryHandler,
|
||||
SearchMyIssuesQueryHandler,
|
||||
GetAttachmentQueryHandler,
|
||||
];
|
||||
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
import { lastValueFrom, of, toArray } from 'rxjs';
|
||||
import {
|
||||
FakeUserDirectory,
|
||||
InMemoryAttachmentStorage,
|
||||
InMemoryEventStore,
|
||||
InMemoryEventStorePublisher,
|
||||
InMemoryIssueNumbers,
|
||||
@@ -51,12 +52,14 @@ import { ReleaseIssuesRepository } from '../ports/release-issues.repository';
|
||||
import { ReleaseNamesRepository } from '../ports/release-names.repository';
|
||||
import { TrackerStreamsRepository } from '../ports/tracker-streams.repository';
|
||||
import { UserDirectory } from '../ports/user-directory';
|
||||
import { AttachmentStorage } from '../ports/attachment-storage';
|
||||
import { ProjectDeletionSaga } from './project-deletion.saga';
|
||||
import { ReleaseArchivedSaga } from './release-archived.saga';
|
||||
import { UserDeactivatedSaga } from './user-deactivated.saga';
|
||||
|
||||
async function setup() {
|
||||
const store = new InMemoryEventStore();
|
||||
const files = new InMemoryAttachmentStorage();
|
||||
const users = new FakeUserDirectory().add('owner').add('dev').add('qa');
|
||||
// Read model double for the user saga: open tickets are tracked by the test.
|
||||
const openAssigned = new Map<string, string[]>();
|
||||
@@ -71,6 +74,7 @@ async function setup() {
|
||||
WriteAccess,
|
||||
AggregateRehydrator,
|
||||
{ provide: EventStore, useValue: store },
|
||||
{ provide: AttachmentStorage, useValue: files },
|
||||
{ provide: UserDirectory, useValue: users },
|
||||
{ provide: ProjectKeysRepository, useClass: InMemoryProjectKeys },
|
||||
{ provide: IssueNumbersRepository, useClass: InMemoryIssueNumbers },
|
||||
|
||||
@@ -7,6 +7,9 @@ import {
|
||||
SerializableEvent,
|
||||
VersionedAggregateRoot,
|
||||
} from '@task-stream/api/shared/domain';
|
||||
import { Readable } from 'node:stream';
|
||||
import { NotFoundError } from '@task-stream/api/shared/domain';
|
||||
import { AttachmentStorage } from '../lib/ports/attachment-storage';
|
||||
import { IssueNumbersRepository } from '../lib/ports/issue-numbers.repository';
|
||||
import { ProjectKeysRepository } from '../lib/ports/project-keys.repository';
|
||||
import { ReleaseIssuesRepository } from '../lib/ports/release-issues.repository';
|
||||
@@ -244,3 +247,28 @@ export class InMemoryTrackerStreams extends TrackerStreamsRepository {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Attachment storage double: files in a map, keyed like on disk. */
|
||||
export class InMemoryAttachmentStorage extends AttachmentStorage {
|
||||
readonly files = new Map<string, Buffer>();
|
||||
|
||||
async put(key: string, content: Buffer) {
|
||||
this.files.set(key, content);
|
||||
}
|
||||
|
||||
async read(key: string) {
|
||||
const content = this.files.get(key);
|
||||
if (!content) throw new NotFoundError('Attachment', key);
|
||||
return Readable.from(content);
|
||||
}
|
||||
|
||||
async remove(key: string) {
|
||||
this.files.delete(key);
|
||||
}
|
||||
|
||||
async removePrefix(prefix: string) {
|
||||
for (const key of [...this.files.keys()]) {
|
||||
if (key.startsWith(prefix)) this.files.delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ export * from './lib/project/project';
|
||||
export * from './lib/project/project-role';
|
||||
export * from './lib/issue/issue';
|
||||
export * from './lib/issue/issue.enums';
|
||||
export * from './lib/issue/issue-attachment';
|
||||
export * from './lib/project/project-settings';
|
||||
export * from './lib/comment/comment';
|
||||
export * from './lib/release/release';
|
||||
|
||||
@@ -22,3 +22,5 @@ export * from './release-archived.event';
|
||||
export * from './project-deleted.event';
|
||||
export * from './issue-deleted.event';
|
||||
export * from './release-deleted.event';
|
||||
export * from './issue-attachment-added.event';
|
||||
export * from './issue-attachment-removed.event';
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import { AutowiredEvent } from '@task-stream/api/shared/domain';
|
||||
import type { IssueAttachment } from '../issue/issue-attachment';
|
||||
import { TrackerEvent } from './tracker.event';
|
||||
|
||||
/** A file was attached to a ticket (or to one of its comments). */
|
||||
@AutowiredEvent
|
||||
export class IssueAttachmentAddedEvent extends TrackerEvent {
|
||||
constructor(
|
||||
actorId: string,
|
||||
issueId: string,
|
||||
projectId: string,
|
||||
readonly attachment: IssueAttachment,
|
||||
) {
|
||||
super(actorId, issueId, projectId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { AutowiredEvent } from '@task-stream/api/shared/domain';
|
||||
import { TrackerEvent } from './tracker.event';
|
||||
|
||||
/** A file was removed from a ticket. */
|
||||
@AutowiredEvent
|
||||
export class IssueAttachmentRemovedEvent extends TrackerEvent {
|
||||
constructor(
|
||||
actorId: string,
|
||||
issueId: string,
|
||||
projectId: string,
|
||||
readonly attachmentId: string,
|
||||
readonly fileName: string,
|
||||
) {
|
||||
super(actorId, issueId, projectId);
|
||||
}
|
||||
}
|
||||
35
libs/api/tracker/domain/src/lib/issue/issue-attachment.ts
Normal file
35
libs/api/tracker/domain/src/lib/issue/issue-attachment.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import { assertThat } from '@task-stream/api/shared/domain';
|
||||
|
||||
/**
|
||||
* A file attached to a ticket — a screenshot, a log, a short video. The bytes
|
||||
* live in the attachment storage; the ticket only records that they exist.
|
||||
* `commentId` places it under one of the ticket's comments.
|
||||
*/
|
||||
export interface IssueAttachment {
|
||||
id: string;
|
||||
fileName: string;
|
||||
mimeType: string;
|
||||
/** Bytes. */
|
||||
size: number;
|
||||
uploadedBy: string;
|
||||
uploadedAt: string;
|
||||
commentId: string | null;
|
||||
}
|
||||
|
||||
/** A ticket keeps at most this many files. */
|
||||
export const MAX_ATTACHMENTS_PER_ISSUE = 50;
|
||||
|
||||
/** Trims the name and keeps only its last path segment. */
|
||||
export function normalizeAttachment(
|
||||
attachment: IssueAttachment,
|
||||
): IssueAttachment {
|
||||
const fileName =
|
||||
attachment.fileName.split(/[\\/]/).pop()?.trim().slice(0, 200) ?? '';
|
||||
assertThat(fileName.length > 0, 'An attachment needs a file name');
|
||||
assertThat(attachment.size > 0, 'An attachment cannot be empty');
|
||||
return {
|
||||
...attachment,
|
||||
fileName,
|
||||
mimeType: attachment.mimeType || 'application/octet-stream',
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
BusinessRuleError,
|
||||
ForbiddenError,
|
||||
ValidationError,
|
||||
} from '@task-stream/api/shared/domain';
|
||||
import { IssueCreatedEvent } from '../events/issue-created.event';
|
||||
@@ -154,4 +155,55 @@ describe('Issue', () => {
|
||||
});
|
||||
expect(rebuilt.getUncommittedEvents()).toHaveLength(0);
|
||||
});
|
||||
|
||||
describe('attachments', () => {
|
||||
const file = (id: string, uploadedBy = 'u-qa') => ({
|
||||
id,
|
||||
fileName: 'C:\\Users\\qa\\captura login.png',
|
||||
mimeType: 'image/png',
|
||||
size: 2048,
|
||||
uploadedBy,
|
||||
uploadedAt: '2026-10-01T10:00:00.000Z',
|
||||
commentId: null,
|
||||
});
|
||||
|
||||
it('records a file with its name cleaned up, once', () => {
|
||||
const issue = newIssue();
|
||||
issue.attach('u-qa', file('a-1'));
|
||||
issue.attach('u-qa', file('a-1'));
|
||||
|
||||
expect(issue.attachments).toHaveLength(1);
|
||||
expect(issue.attachments[0].fileName).toBe('captura login.png');
|
||||
});
|
||||
|
||||
it('lets the uploader or a manager remove it, nobody else', () => {
|
||||
const issue = newIssue();
|
||||
issue.attach('u-qa', file('a-1'));
|
||||
|
||||
expect(() => issue.detach('u-dev', 'a-1', false)).toThrow(ForbiddenError);
|
||||
issue.detach('u-dev', 'a-1', true);
|
||||
|
||||
expect(issue.attachments).toEqual([]);
|
||||
expect(() => issue.detach('u-qa', 'a-1', true)).toThrow(
|
||||
BusinessRuleError,
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects empty files', () => {
|
||||
expect(() =>
|
||||
newIssue().attach('u-qa', { ...file('a-1'), size: 0 }),
|
||||
).toThrow(ValidationError);
|
||||
});
|
||||
|
||||
it('survives a replay', () => {
|
||||
const issue = newIssue();
|
||||
issue.attach('u-qa', file('a-1'));
|
||||
issue.attach('u-qa', file('a-2'));
|
||||
issue.detach('u-qa', 'a-1', false);
|
||||
|
||||
const { rebuilt } = replay(issue, Issue);
|
||||
|
||||
expect(rebuilt.attachments.map((a) => a.id)).toEqual(['a-2']);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import {
|
||||
BusinessRuleError,
|
||||
ForbiddenError,
|
||||
VersionedAggregateRoot,
|
||||
assertThat,
|
||||
} from '@task-stream/api/shared/domain';
|
||||
import { IssueAssignedEvent } from '../events/issue-assigned.event';
|
||||
import { IssueAttachmentAddedEvent } from '../events/issue-attachment-added.event';
|
||||
import { IssueAttachmentRemovedEvent } from '../events/issue-attachment-removed.event';
|
||||
import { IssueCreatedEvent } from '../events/issue-created.event';
|
||||
import { IssueDeletedEvent } from '../events/issue-deleted.event';
|
||||
import { IssueLinkedEvent } from '../events/issue-linked.event';
|
||||
@@ -12,6 +15,11 @@ import { IssueStatusChangedEvent } from '../events/issue-status-changed.event';
|
||||
import { IssueUnlinkedEvent } from '../events/issue-unlinked.event';
|
||||
import { IssueUpdatedEvent } from '../events/issue-updated.event';
|
||||
import { ProjectWorkflow } from '../project/project-settings';
|
||||
import {
|
||||
IssueAttachment,
|
||||
MAX_ATTACHMENTS_PER_ISSUE,
|
||||
normalizeAttachment,
|
||||
} from './issue-attachment';
|
||||
import { IssueLinkType, IssuePriority } from './issue.enums';
|
||||
|
||||
export interface IssueLink {
|
||||
@@ -82,6 +90,7 @@ export class Issue extends VersionedAggregateRoot implements IssueProps {
|
||||
public storyPoints: number | null = null;
|
||||
public dueDate: string | null = null;
|
||||
public links: IssueLink[] = [];
|
||||
public attachments: IssueAttachment[] = [];
|
||||
public createdAt!: string;
|
||||
public updatedAt!: string;
|
||||
public deleted = false;
|
||||
@@ -216,6 +225,43 @@ export class Issue extends VersionedAggregateRoot implements IssueProps {
|
||||
);
|
||||
}
|
||||
|
||||
/** Records a file stored for this ticket (or one of its comments). */
|
||||
attach(actorId: string, attachment: IssueAttachment): void {
|
||||
const next = normalizeAttachment(attachment);
|
||||
if (this.attachments.some((a) => a.id === next.id)) return;
|
||||
if (this.attachments.length >= MAX_ATTACHMENTS_PER_ISSUE) {
|
||||
throw new BusinessRuleError(
|
||||
`${this.key} already has ${MAX_ATTACHMENTS_PER_ISSUE} attachments; remove one first`,
|
||||
);
|
||||
}
|
||||
this.apply(
|
||||
new IssueAttachmentAddedEvent(actorId, this.id, this.projectId, next),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a file. Whoever uploaded it may, and so may whoever manages the
|
||||
* project (`canManage`).
|
||||
*/
|
||||
detach(actorId: string, attachmentId: string, canManage: boolean): void {
|
||||
const attachment = this.attachments.find((a) => a.id === attachmentId);
|
||||
if (!attachment) throw new BusinessRuleError('Attachment not found');
|
||||
if (attachment.uploadedBy !== actorId && !canManage) {
|
||||
throw new ForbiddenError(
|
||||
'Only whoever uploaded a file, or a project admin, can remove it',
|
||||
);
|
||||
}
|
||||
this.apply(
|
||||
new IssueAttachmentRemovedEvent(
|
||||
actorId,
|
||||
this.id,
|
||||
this.projectId,
|
||||
attachment.id,
|
||||
attachment.fileName,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** Deletes the ticket (its project was deleted). Idempotent. */
|
||||
delete(actorId: string): void {
|
||||
if (this.deleted) return;
|
||||
@@ -276,6 +322,18 @@ export class Issue extends VersionedAggregateRoot implements IssueProps {
|
||||
this.updatedAt = event.occurredAt;
|
||||
}
|
||||
|
||||
onIssueAttachmentAddedEvent(event: IssueAttachmentAddedEvent): void {
|
||||
this.attachments = [...this.attachments, { ...event.attachment }];
|
||||
this.updatedAt = event.occurredAt;
|
||||
}
|
||||
|
||||
onIssueAttachmentRemovedEvent(event: IssueAttachmentRemovedEvent): void {
|
||||
this.attachments = this.attachments.filter(
|
||||
(a) => a.id !== event.attachmentId,
|
||||
);
|
||||
this.updatedAt = event.occurredAt;
|
||||
}
|
||||
|
||||
onIssueDeletedEvent(): void {
|
||||
this.deleted = true;
|
||||
}
|
||||
|
||||
@@ -12,6 +12,17 @@ export class IssueLinkReadModel {
|
||||
issueKey!: string;
|
||||
}
|
||||
|
||||
export class AttachmentReadModel {
|
||||
id!: string;
|
||||
fileName!: string;
|
||||
mimeType!: string;
|
||||
size!: number;
|
||||
uploadedBy!: UserRefReadModel;
|
||||
uploadedAt!: string;
|
||||
/** Shown under this comment when set. */
|
||||
commentId!: string | null;
|
||||
}
|
||||
|
||||
export class IssueReadModel {
|
||||
id!: string;
|
||||
projectId!: string;
|
||||
@@ -35,6 +46,7 @@ export class IssueReadModel {
|
||||
storyPoints!: number | null;
|
||||
dueDate!: string | null;
|
||||
links!: IssueLinkReadModel[];
|
||||
attachments!: AttachmentReadModel[];
|
||||
commentCount!: number;
|
||||
createdAt!: string;
|
||||
updatedAt!: string;
|
||||
|
||||
@@ -69,6 +69,18 @@ export const IssueSchema = new Schema<IssueDoc>(
|
||||
release: { _id: false, id: String, name: String },
|
||||
outwardLinks: [link],
|
||||
inwardLinks: [link],
|
||||
attachments: [
|
||||
{
|
||||
_id: false,
|
||||
id: String,
|
||||
fileName: String,
|
||||
mimeType: String,
|
||||
size: Number,
|
||||
uploadedBy: userRef,
|
||||
uploadedAt: String,
|
||||
commentId: String,
|
||||
},
|
||||
],
|
||||
labels: [String],
|
||||
version: Number,
|
||||
},
|
||||
@@ -137,5 +149,7 @@ export function issueFromDoc(doc: IssueDoc): IssueReadModel {
|
||||
id: _id,
|
||||
...rest,
|
||||
links: [...(outwardLinks ?? []), ...(inwardLinks ?? [])],
|
||||
// Tickets projected before attachments existed have none.
|
||||
attachments: rest.attachments ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
} from '@task-stream/api/tracker/application';
|
||||
import {
|
||||
ActivityReadModel,
|
||||
AttachmentReadModel,
|
||||
CommentReadModel,
|
||||
IssueLinkReadModel,
|
||||
IssueReadModel,
|
||||
@@ -99,14 +100,29 @@ export class MongoUpsertMaterializedIssueRepository extends UpsertMaterializedIs
|
||||
version,
|
||||
...fields
|
||||
}: Pick<IssueReadModel, 'id' | 'version'> &
|
||||
Partial<Omit<IssueReadModel, 'links' | 'commentCount'>>) {
|
||||
Partial<Omit<IssueReadModel, 'links' | 'commentCount' | 'attachments'>>) {
|
||||
await upsertIfNewer(this.issues, id, version, fields, {
|
||||
outwardLinks: [],
|
||||
inwardLinks: [],
|
||||
attachments: [],
|
||||
commentCount: 0,
|
||||
});
|
||||
}
|
||||
|
||||
async addAttachment(issueId: string, attachment: AttachmentReadModel) {
|
||||
await this.issues.updateOne(
|
||||
{ _id: issueId, 'attachments.id': { $ne: attachment.id } },
|
||||
{ $push: { attachments: attachment } },
|
||||
);
|
||||
}
|
||||
|
||||
async removeAttachment(issueId: string, attachmentId: string) {
|
||||
await this.issues.updateOne(
|
||||
{ _id: issueId },
|
||||
{ $pull: { attachments: { id: attachmentId } } },
|
||||
);
|
||||
}
|
||||
|
||||
async addLink(issueId: string, link: IssueLinkReadModel) {
|
||||
const field = link.direction === 'OUTWARD' ? 'outwardLinks' : 'inwardLinks';
|
||||
await this.issues.updateOne(
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { createReadStream } from 'node:fs';
|
||||
import { mkdir, rm, stat, writeFile } from 'node:fs/promises';
|
||||
import { dirname, resolve, sep } from 'node:path';
|
||||
import type { Readable } from 'node:stream';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { NotFoundError } from '@task-stream/api/shared/domain';
|
||||
import { AttachmentStorage } from '@task-stream/api/tracker/application';
|
||||
|
||||
/**
|
||||
* Attached files on disk, under ATTACHMENTS_DIR (a volume in Docker). Keys
|
||||
* come from ids this API generated, but are still checked to stay inside the
|
||||
* folder: a key is never trusted to be a path.
|
||||
*/
|
||||
@Injectable()
|
||||
export class FileSystemAttachmentStorage extends AttachmentStorage {
|
||||
private readonly root: string;
|
||||
|
||||
constructor(config: ConfigService) {
|
||||
super();
|
||||
this.root = resolve(
|
||||
config.get<string>('ATTACHMENTS_DIR') || 'data/attachments',
|
||||
);
|
||||
}
|
||||
|
||||
async put(key: string, content: Buffer): Promise<void> {
|
||||
const path = this.pathOf(key);
|
||||
await mkdir(dirname(path), { recursive: true });
|
||||
await writeFile(path, content, { flag: 'wx' });
|
||||
}
|
||||
|
||||
async read(key: string): Promise<Readable> {
|
||||
const path = this.pathOf(key);
|
||||
try {
|
||||
await stat(path);
|
||||
} catch {
|
||||
throw new NotFoundError('Attachment', key.split('/').pop() ?? key);
|
||||
}
|
||||
return createReadStream(path);
|
||||
}
|
||||
|
||||
async remove(key: string): Promise<void> {
|
||||
await rm(this.pathOf(key), { force: true });
|
||||
}
|
||||
|
||||
async removePrefix(prefix: string): Promise<void> {
|
||||
await rm(this.pathOf(prefix), { recursive: true, force: true });
|
||||
}
|
||||
|
||||
private pathOf(key: string): string {
|
||||
const path = resolve(this.root, key);
|
||||
if (path !== this.root && !path.startsWith(this.root + sep)) {
|
||||
throw new Error(`Attachment key escapes the storage folder: ${key}`);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { CqrsModule } from '@nestjs/cqrs';
|
||||
import { MongooseModule } from '@nestjs/mongoose';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import {
|
||||
AttachmentStorage,
|
||||
ChangeFeed,
|
||||
FindActivityRepository,
|
||||
FindCommentsRepository,
|
||||
@@ -51,6 +52,7 @@ import {
|
||||
import { PostgresReleaseIssuesRepository } from './postgres/release-issues.repository';
|
||||
import { PostgresTrackerStreamsRepository } from './postgres/tracker-streams.repository';
|
||||
import { RedisChangeFeed } from './realtime/redis-change-feed';
|
||||
import { FileSystemAttachmentStorage } from './storage/file-system-attachment.storage';
|
||||
|
||||
const PORTS = [
|
||||
// Write side lookups → PostgreSQL (aggregates themselves live in the event store)
|
||||
@@ -96,6 +98,8 @@ const PORTS = [
|
||||
provide: UpsertMaterializedTimelineRepository,
|
||||
useClass: MongoUpsertMaterializedTimelineRepository,
|
||||
},
|
||||
// Attached files → disk (ATTACHMENTS_DIR)
|
||||
{ provide: AttachmentStorage, useClass: FileSystemAttachmentStorage },
|
||||
// Realtime → Redis pub/sub
|
||||
{ provide: ChangeFeed, useClass: RedisChangeFeed },
|
||||
// Identity context (anti-corruption layer)
|
||||
|
||||
@@ -183,6 +183,18 @@ export class IssueResolver {
|
||||
);
|
||||
}
|
||||
|
||||
@Mutation(() => CommandResultGql, {
|
||||
description:
|
||||
'Remove a file from a ticket (whoever uploaded it, or an owner/admin). Upload with the REST API.',
|
||||
})
|
||||
removeAttachment(
|
||||
@CurrentUser() me: User,
|
||||
@Args('issueId', { type: () => ID }) issueId: string,
|
||||
@Args('attachmentId', { type: () => ID }) attachmentId: string,
|
||||
) {
|
||||
return this.issuesService.detach(me.id, issueId, attachmentId);
|
||||
}
|
||||
|
||||
@Mutation(() => CommandResultGql, {
|
||||
description: 'Assign (or unassign with null) a project member',
|
||||
})
|
||||
|
||||
@@ -91,6 +91,24 @@ export class IssueLinkGql {
|
||||
@Field() issueKey!: string;
|
||||
}
|
||||
|
||||
@ObjectType('Attachment', {
|
||||
description:
|
||||
'A file on a ticket. Download it from the REST API: GET /api/issues/{issueId}/attachments/{id}',
|
||||
})
|
||||
export class AttachmentGql {
|
||||
@Field(() => ID) id!: string;
|
||||
@Field() fileName!: string;
|
||||
@Field() mimeType!: string;
|
||||
@Field(() => Int, { description: 'Bytes' }) size!: number;
|
||||
@Field(() => UserRefGql) uploadedBy!: UserRefGql;
|
||||
@Field() uploadedAt!: string;
|
||||
@Field(() => ID, {
|
||||
nullable: true,
|
||||
description: 'The comment it was attached to, if any',
|
||||
})
|
||||
commentId!: string | null;
|
||||
}
|
||||
|
||||
@ObjectType('ReleaseRef')
|
||||
export class ReleaseRefGql {
|
||||
@Field(() => ID) id!: string;
|
||||
@@ -123,6 +141,7 @@ export class IssueGql {
|
||||
@Field(() => Int, { nullable: true }) storyPoints!: number | null;
|
||||
@Field(() => String, { nullable: true }) dueDate!: string | null;
|
||||
@Field(() => [IssueLinkGql]) links!: IssueLinkGql[];
|
||||
@Field(() => [AttachmentGql]) attachments!: AttachmentGql[];
|
||||
@Field(() => Int) commentCount!: number;
|
||||
@Field() createdAt!: string;
|
||||
@Field() updatedAt!: string;
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Param,
|
||||
Post,
|
||||
Res,
|
||||
StreamableFile,
|
||||
UploadedFile,
|
||||
UseInterceptors,
|
||||
} from '@nestjs/common';
|
||||
import { FileInterceptor } from '@nestjs/platform-express';
|
||||
import {
|
||||
ApiBody,
|
||||
ApiConsumes,
|
||||
ApiCreatedResponse,
|
||||
ApiOkResponse,
|
||||
ApiOperation,
|
||||
ApiParam,
|
||||
ApiProduces,
|
||||
ApiTags,
|
||||
} from '@nestjs/swagger';
|
||||
import { User } from '@task-stream/api/identity/domain';
|
||||
import {
|
||||
ApiOptionalPireonAuth,
|
||||
ApiPireonAuth,
|
||||
CurrentUser,
|
||||
} from '@task-stream/api/identity/presenters';
|
||||
import {
|
||||
ApiCommandErrors,
|
||||
ApiReadErrors,
|
||||
} from '@task-stream/api/shared/presenters';
|
||||
import { ValidationError } from '@task-stream/api/shared/domain';
|
||||
import { IssuesService } from '@task-stream/api/tracker/application';
|
||||
import type { Response } from 'express';
|
||||
import { viewerOf } from '../common/viewer';
|
||||
import { AttachFileDto } from './dto/requests.dto';
|
||||
import { CommandResultDto } from './dto/responses.dto';
|
||||
import { Refs } from './refs';
|
||||
|
||||
const ISSUE = ApiParam({
|
||||
name: 'issue',
|
||||
description: 'Ticket id or key',
|
||||
example: 'WEB-12',
|
||||
});
|
||||
|
||||
/** What multer hands over for one uploaded field. */
|
||||
interface UploadedPart {
|
||||
originalname: string;
|
||||
mimetype: string;
|
||||
buffer: Buffer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Types a browser may show in place. Anything else — HTML, SVG, scripts — is
|
||||
* always downloaded: a file someone uploaded must never run in this origin.
|
||||
*/
|
||||
const SHOWN_INLINE =
|
||||
/^(image\/(png|jpe?g|gif|webp|avif)|video\/(mp4|webm)|audio\/(mpeg|ogg|wav)|application\/pdf|text\/plain)$/;
|
||||
|
||||
/** REST adapter for a ticket's files: uploaded here, listed on the ticket. */
|
||||
@ApiTags('Issues')
|
||||
@ApiPireonAuth()
|
||||
@Controller('issues/:issue/attachments')
|
||||
export class AttachmentsController {
|
||||
constructor(
|
||||
private readonly issues: IssuesService,
|
||||
private readonly refs: Refs,
|
||||
) {}
|
||||
|
||||
@Post()
|
||||
@ISSUE
|
||||
@UseInterceptors(FileInterceptor('file'))
|
||||
@ApiConsumes('multipart/form-data')
|
||||
@ApiBody({ type: AttachFileDto })
|
||||
@ApiOperation({
|
||||
summary: 'Attach a file to a ticket (members)',
|
||||
description:
|
||||
'Multipart with the file as `file` and, optionally, `commentId` to place it under a comment. ' +
|
||||
'Up to ATTACHMENTS_MAX_MB megabytes (25 by default) and 50 files per ticket.',
|
||||
})
|
||||
@ApiCreatedResponse({ type: CommandResultDto })
|
||||
@ApiCommandErrors()
|
||||
async attach(
|
||||
@CurrentUser() me: User,
|
||||
@Param('issue') issue: string,
|
||||
@UploadedFile() file: UploadedPart | undefined,
|
||||
@Body() body: AttachFileDto,
|
||||
) {
|
||||
if (!file) throw new ValidationError('Send the file as `file`');
|
||||
return this.issues.attach(
|
||||
me.id,
|
||||
await this.refs.issueId(me.id, issue),
|
||||
{
|
||||
fileName: Buffer.from(file.originalname, 'latin1').toString('utf8'),
|
||||
mimeType: file.mimetype,
|
||||
content: file.buffer,
|
||||
},
|
||||
body.commentId || null,
|
||||
);
|
||||
}
|
||||
|
||||
@Get(':attachmentId')
|
||||
@ApiOptionalPireonAuth()
|
||||
@ISSUE
|
||||
@ApiOperation({ summary: "Download one of a ticket's files" })
|
||||
@ApiProduces('application/octet-stream')
|
||||
@ApiOkResponse({ description: 'The file' })
|
||||
@ApiReadErrors()
|
||||
async download(
|
||||
@CurrentUser() me: User | undefined,
|
||||
@Param('issue') issue: string,
|
||||
@Param('attachmentId') attachmentId: string,
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
): Promise<StreamableFile> {
|
||||
const viewer = viewerOf(me);
|
||||
const { attachment, content } = await this.issues.download(
|
||||
viewer,
|
||||
await this.refs.issueId(viewer, issue),
|
||||
attachmentId,
|
||||
);
|
||||
const inline = SHOWN_INLINE.test(attachment.mimeType);
|
||||
res.set({
|
||||
'Content-Type': inline ? attachment.mimeType : 'application/octet-stream',
|
||||
'Content-Length': String(attachment.size),
|
||||
'Content-Disposition': `${inline ? 'inline' : 'attachment'}; filename="${asciiName(attachment.fileName)}"; filename*=UTF-8''${encodeURIComponent(attachment.fileName)}`,
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
'Content-Security-Policy': "default-src 'none'; sandbox",
|
||||
'Cache-Control': 'private, max-age=3600',
|
||||
});
|
||||
return new StreamableFile(content);
|
||||
}
|
||||
|
||||
@Delete(':attachmentId')
|
||||
@ISSUE
|
||||
@ApiOperation({
|
||||
summary: 'Remove a file (whoever uploaded it, or an owner/admin)',
|
||||
})
|
||||
@ApiOkResponse({ type: CommandResultDto })
|
||||
@ApiCommandErrors()
|
||||
async remove(
|
||||
@CurrentUser() me: User,
|
||||
@Param('issue') issue: string,
|
||||
@Param('attachmentId') attachmentId: string,
|
||||
) {
|
||||
return this.issues.detach(
|
||||
me.id,
|
||||
await this.refs.issueId(me.id, issue),
|
||||
attachmentId,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** The name with anything outside printable ASCII replaced, for old clients. */
|
||||
function asciiName(name: string): string {
|
||||
return name.replace(/[^\x20-\x7e]|["\\]/g, '_');
|
||||
}
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
IsInt,
|
||||
IsISO8601,
|
||||
IsOptional,
|
||||
IsUUID,
|
||||
IsString,
|
||||
IsUrl,
|
||||
Matches,
|
||||
@@ -576,6 +577,20 @@ export class LinkTypeParamDto {
|
||||
type!: IssueLinkType;
|
||||
}
|
||||
|
||||
/** Multipart body of an upload; the file itself travels as `file`. */
|
||||
export class AttachFileDto {
|
||||
@ApiProperty({ type: 'string', format: 'binary', description: 'The file' })
|
||||
file?: unknown;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
format: 'uuid',
|
||||
description: "One of the ticket's comments, to show the file under it",
|
||||
})
|
||||
@IsOptional()
|
||||
@IsUUID()
|
||||
commentId?: string;
|
||||
}
|
||||
|
||||
export class CommentBodyDto {
|
||||
@ApiProperty({ example: 'Reproducido en Safari 17.', maxLength: 20000 })
|
||||
@IsString()
|
||||
|
||||
@@ -106,6 +106,22 @@ export class ReleaseRefDto {
|
||||
@ApiProperty({ example: 'v1.4.0' }) name!: string;
|
||||
}
|
||||
|
||||
export class AttachmentDto {
|
||||
@ApiProperty({ format: 'uuid' }) id!: string;
|
||||
@ApiProperty({ example: 'captura-login.png' }) fileName!: string;
|
||||
@ApiProperty({ example: 'image/png' }) mimeType!: string;
|
||||
@ApiProperty({ description: 'Bytes', example: 48213 }) size!: number;
|
||||
@ApiProperty({ type: UserRefDto }) uploadedBy!: UserRefDto;
|
||||
@ApiProperty({ format: 'date-time' }) uploadedAt!: string;
|
||||
@ApiProperty({
|
||||
type: String,
|
||||
nullable: true,
|
||||
format: 'uuid',
|
||||
description: 'The comment it was attached to, if any',
|
||||
})
|
||||
commentId!: string | null;
|
||||
}
|
||||
|
||||
export class IssueDto {
|
||||
@ApiProperty({ format: 'uuid' }) id!: string;
|
||||
@ApiProperty({ format: 'uuid' }) projectId!: string;
|
||||
@@ -141,6 +157,7 @@ export class IssueDto {
|
||||
@ApiProperty({ type: String, nullable: true, format: 'date' })
|
||||
dueDate!: string | null;
|
||||
@ApiProperty({ type: [IssueLinkDto] }) links!: IssueLinkDto[];
|
||||
@ApiProperty({ type: [AttachmentDto] }) attachments!: AttachmentDto[];
|
||||
@ApiProperty() commentCount!: number;
|
||||
@ApiProperty({ format: 'date-time' }) createdAt!: string;
|
||||
@ApiProperty({ format: 'date-time' }) updatedAt!: string;
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import { DynamicModule, Module, Type } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { MulterModule } from '@nestjs/platform-express';
|
||||
import './graphql/enums';
|
||||
import { CommentResolver } from './graphql/comment.resolver';
|
||||
import { IssueResolver } from './graphql/issue.resolver';
|
||||
import { ProjectResolver } from './graphql/project.resolver';
|
||||
import { ReleaseResolver } from './graphql/release.resolver';
|
||||
import { SubscriptionResolver } from './graphql/subscription.resolver';
|
||||
import { AttachmentsController } from './http/attachments.controller';
|
||||
import { CommentsController } from './http/comments.controller';
|
||||
import { IssuesController } from './http/issues.controller';
|
||||
import { ExploreController } from './http/explore.controller';
|
||||
@@ -18,9 +21,24 @@ import { ReleasesController } from './http/releases.controller';
|
||||
* application services.
|
||||
*/
|
||||
@Module({
|
||||
imports: [
|
||||
// Uploads stay in memory until the command stores them; the size limit
|
||||
// is enforced here, before a byte reaches the application.
|
||||
MulterModule.registerAsync({
|
||||
inject: [ConfigService],
|
||||
useFactory: (config: ConfigService) => ({
|
||||
limits: {
|
||||
fileSize:
|
||||
(config.get<number>('ATTACHMENTS_MAX_MB') ?? 25) * 1024 * 1024,
|
||||
files: 1,
|
||||
},
|
||||
}),
|
||||
}),
|
||||
],
|
||||
controllers: [
|
||||
ProjectsController,
|
||||
IssuesController,
|
||||
AttachmentsController,
|
||||
CommentsController,
|
||||
ReleasesController,
|
||||
ExploreController,
|
||||
@@ -38,6 +56,9 @@ export class TrackerPresentersModule {
|
||||
static withApplication(
|
||||
applicationModule: Type | DynamicModule,
|
||||
): DynamicModule {
|
||||
return { module: TrackerPresentersModule, imports: [applicationModule] };
|
||||
return {
|
||||
module: TrackerPresentersModule,
|
||||
imports: [applicationModule],
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,6 +87,10 @@ export const APP_ICONS: Record<string, string> = {
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><circle cx="9" cy="8" r="3.5"/><path d="M2.5 20a6.5 6.5 0 0 1 13 0M16 4.6a3.5 3.5 0 0 1 0 6.8M18.5 14.5a6.5 6.5 0 0 1 3 5.5"/></svg>',
|
||||
logout:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M15 4h3a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2h-3M10 16l-4-4 4-4M6 12h10"/></svg>',
|
||||
image:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="16" rx="2"/><circle cx="8.5" cy="9.5" r="1.5"/><path d="m21 16-5-5-9 9"/></svg>',
|
||||
paperclip:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="m20 11.5-8.4 8.4a5 5 0 0 1-7-7l8.4-8.4a3.3 3.3 0 0 1 4.7 4.7l-8.4 8.4a1.7 1.7 0 0 1-2.4-2.4l7.8-7.7"/></svg>',
|
||||
trash:
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M4 7h16M9 7V4h6v3M6 7l1 13h10l1-13M10 11v6M14 11v6"/></svg>',
|
||||
edit: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M4 20h4L19 9l-4-4L4 16v4ZM13.5 6.5l4 4"/></svg>',
|
||||
|
||||
@@ -29,7 +29,21 @@ export const issuePageEvents = eventGroup({
|
||||
issueId: string;
|
||||
releaseId: string | null;
|
||||
}>(),
|
||||
commentAddRequested: type<{ issueId: string; body: string }>(),
|
||||
commentAddRequested: type<{
|
||||
issueId: string;
|
||||
body: string;
|
||||
/** Uploaded under the new comment once it exists. */
|
||||
files?: File[];
|
||||
}>(),
|
||||
attachRequested: type<{
|
||||
issueId: string;
|
||||
files: File[];
|
||||
commentId?: string | null;
|
||||
}>(),
|
||||
attachmentRemoveRequested: type<{
|
||||
issueId: string;
|
||||
attachmentId: string;
|
||||
}>(),
|
||||
commentEditRequested: type<{ commentId: string; body: string }>(),
|
||||
commentDeleteRequested: type<{ commentId: string }>(),
|
||||
},
|
||||
|
||||
@@ -4,6 +4,7 @@ import { Events } from '@ngrx/signals/events';
|
||||
import { AuthFacade } from '@task-stream/web/identity/application';
|
||||
import {
|
||||
ActivityGateway,
|
||||
AttachmentsGateway,
|
||||
CommentsGateway,
|
||||
IssuesGateway,
|
||||
Project,
|
||||
@@ -45,7 +46,15 @@ function gateways() {
|
||||
issue: vi.fn(() => of(issue)),
|
||||
changeStatus: vi.fn(() => of(ok)),
|
||||
},
|
||||
list: { list: vi.fn(() => of([])) },
|
||||
list: {
|
||||
list: vi.fn(() => of([])),
|
||||
add: vi.fn(() => of({ ...ok, id: 'c1' })),
|
||||
},
|
||||
attachments: {
|
||||
upload: vi.fn(() => of(ok)),
|
||||
download: vi.fn(() => of(new Blob(['x']))),
|
||||
remove: vi.fn(() => of(ok)),
|
||||
},
|
||||
realtime: {
|
||||
issueChanges: () => NEVER,
|
||||
commentChanges: () => NEVER,
|
||||
@@ -80,6 +89,7 @@ function setup() {
|
||||
{ provide: ReleasesGateway, useValue: fakes.list },
|
||||
{ provide: ActivityGateway, useValue: fakes.list },
|
||||
{ provide: CommentsGateway, useValue: fakes.list },
|
||||
{ provide: AttachmentsGateway, useValue: fakes.attachments },
|
||||
{ provide: UsersGateway, useValue: { search: () => of([]) } },
|
||||
{ provide: TrackerRealtimeGateway, useValue: fakes.realtime },
|
||||
{
|
||||
@@ -222,6 +232,24 @@ describe('IssueFacade', () => {
|
||||
reason: 'Falla en Safari',
|
||||
});
|
||||
});
|
||||
|
||||
it('uploads files one by one, and under a new comment when sent with it', () => {
|
||||
const { issue, fakes } = setup();
|
||||
const a = new File(['a'], 'a.png', { type: 'image/png' });
|
||||
const b = new File(['b'], 'b.log', { type: 'text/plain' });
|
||||
|
||||
issue.open('WEB-1');
|
||||
issue.attach([a, b]);
|
||||
issue.addComment('Adjunto la traza', [b]);
|
||||
issue.removeAttachment('f1');
|
||||
|
||||
expect(fakes.attachments.upload.mock.calls).toEqual([
|
||||
['i1', a, null],
|
||||
['i1', b, null],
|
||||
['i1', b, 'c1'],
|
||||
]);
|
||||
expect(fakes.attachments.remove).toHaveBeenCalledWith('i1', 'f1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('HomeFacade', () => {
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import { inject, Injectable, Provider } from '@angular/core';
|
||||
import { injectDispatch } from '@ngrx/signals/events';
|
||||
import {
|
||||
Attachment,
|
||||
AttachmentsGateway,
|
||||
IssueLink,
|
||||
IssueLinkType,
|
||||
UpdateIssueInput,
|
||||
} from '@task-stream/web/tracker/domain';
|
||||
import { Observable } from 'rxjs';
|
||||
import { issuePageEvents } from '../events/issue.events';
|
||||
import { IssueStore } from '../stores/issue.store';
|
||||
|
||||
@@ -16,6 +19,7 @@ import { IssueStore } from '../stores/issue.store';
|
||||
export class IssueFacade {
|
||||
private readonly store = inject(IssueStore);
|
||||
private readonly dispatch = injectDispatch(issuePageEvents);
|
||||
private readonly files = inject(AttachmentsGateway);
|
||||
|
||||
readonly issue = this.store.issue;
|
||||
readonly comments = this.store.comments;
|
||||
@@ -74,12 +78,33 @@ export class IssueFacade {
|
||||
);
|
||||
}
|
||||
|
||||
addComment(body: string): void {
|
||||
/** `files` are attached under the new comment. */
|
||||
addComment(body: string, files: File[] = []): void {
|
||||
this.withIssue((issueId) =>
|
||||
this.dispatch.commentAddRequested({ issueId, body }),
|
||||
this.dispatch.commentAddRequested({ issueId, body, files }),
|
||||
);
|
||||
}
|
||||
|
||||
/** Attaches files to the ticket (or under one of its comments). */
|
||||
attach(files: File[], commentId: string | null = null): void {
|
||||
if (!files.length) return;
|
||||
this.withIssue((issueId) =>
|
||||
this.dispatch.attachRequested({ issueId, files, commentId }),
|
||||
);
|
||||
}
|
||||
|
||||
removeAttachment(attachmentId: string): void {
|
||||
this.withIssue((issueId) =>
|
||||
this.dispatch.attachmentRemoveRequested({ issueId, attachmentId }),
|
||||
);
|
||||
}
|
||||
|
||||
/** The file's bytes, to show an image or save the file. */
|
||||
fileOf(attachment: Attachment): Observable<Blob> {
|
||||
const issueId = this.store.issue()?.id ?? '';
|
||||
return this.files.download(issueId, attachment);
|
||||
}
|
||||
|
||||
editComment(commentId: string, body: string): void {
|
||||
this.dispatch.commentEditRequested({ commentId, body });
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import { AuthFacade } from '@task-stream/web/identity/application';
|
||||
import {
|
||||
Activity,
|
||||
ActivityGateway,
|
||||
AttachmentsGateway,
|
||||
Comment,
|
||||
CommentsGateway,
|
||||
Issue,
|
||||
@@ -18,8 +19,11 @@ import {
|
||||
TrackerRealtimeGateway,
|
||||
} from '@task-stream/web/tracker/domain';
|
||||
import {
|
||||
concatMap,
|
||||
debounceTime,
|
||||
filter,
|
||||
from,
|
||||
last,
|
||||
map,
|
||||
merge,
|
||||
mergeMap,
|
||||
@@ -100,7 +104,18 @@ export const IssueStore = signalStore(
|
||||
activity = inject(ActivityGateway),
|
||||
realtime = inject(TrackerRealtimeGateway),
|
||||
notifications = inject(Notifications),
|
||||
attachments = inject(AttachmentsGateway),
|
||||
) => {
|
||||
/** One file after another: the ticket's version moves with each. */
|
||||
const uploadAll = (
|
||||
issueId: string,
|
||||
files: File[],
|
||||
commentId: string | null = null,
|
||||
) =>
|
||||
from(files).pipe(
|
||||
concatMap((file) => attachments.upload(issueId, file, commentId)),
|
||||
last(),
|
||||
);
|
||||
const fetchIssue = (idOrKey: string) =>
|
||||
issues.issue(idOrKey).pipe(
|
||||
retry({
|
||||
@@ -267,8 +282,48 @@ export const IssueStore = signalStore(
|
||||
.pipe(
|
||||
mergeMap(({ payload }) =>
|
||||
runCommand(
|
||||
comments.add(payload.issueId, payload.body),
|
||||
'Comentario añadido',
|
||||
comments
|
||||
.add(payload.issueId, payload.body)
|
||||
.pipe(
|
||||
concatMap((comment) =>
|
||||
payload.files?.length
|
||||
? uploadAll(
|
||||
payload.issueId,
|
||||
payload.files,
|
||||
comment.id,
|
||||
)
|
||||
: [comment],
|
||||
),
|
||||
),
|
||||
payload.files?.length
|
||||
? 'Comentario y adjuntos añadidos'
|
||||
: 'Comentario añadido',
|
||||
done,
|
||||
failed,
|
||||
),
|
||||
),
|
||||
),
|
||||
events
|
||||
.on(issuePageEvents.attachRequested)
|
||||
.pipe(
|
||||
mergeMap(({ payload }) =>
|
||||
runCommand(
|
||||
uploadAll(payload.issueId, payload.files, payload.commentId),
|
||||
payload.files.length === 1
|
||||
? `${payload.files[0].name} adjuntado`
|
||||
: `${payload.files.length} archivos adjuntados`,
|
||||
done,
|
||||
failed,
|
||||
),
|
||||
),
|
||||
),
|
||||
events
|
||||
.on(issuePageEvents.attachmentRemoveRequested)
|
||||
.pipe(
|
||||
mergeMap(({ payload }) =>
|
||||
runCommand(
|
||||
attachments.remove(payload.issueId, payload.attachmentId),
|
||||
'Adjunto eliminado',
|
||||
done,
|
||||
failed,
|
||||
),
|
||||
|
||||
@@ -65,6 +65,18 @@ export interface IssuePage {
|
||||
total: number;
|
||||
}
|
||||
|
||||
/** A file on a ticket (or under one of its comments). */
|
||||
export interface Attachment {
|
||||
id: string;
|
||||
fileName: string;
|
||||
mimeType: string;
|
||||
/** Bytes. */
|
||||
size: number;
|
||||
uploadedBy: UserRef;
|
||||
uploadedAt: string;
|
||||
commentId: string | null;
|
||||
}
|
||||
|
||||
export interface Issue extends IssueSummary {
|
||||
description: string | null;
|
||||
reporter: UserRef;
|
||||
@@ -72,6 +84,7 @@ export interface Issue extends IssueSummary {
|
||||
storyPoints: number | null;
|
||||
dueDate: string | null;
|
||||
links: IssueLink[];
|
||||
attachments: Attachment[];
|
||||
allowedTransitions: string[];
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Observable } from 'rxjs';
|
||||
import {
|
||||
Activity,
|
||||
Attachment,
|
||||
BoardColumn,
|
||||
Comment,
|
||||
CommandResult,
|
||||
@@ -93,6 +94,21 @@ export abstract class CommentsGateway {
|
||||
abstract remove(commentId: string): Observable<CommandResult>;
|
||||
}
|
||||
|
||||
/** A ticket's files. Uploads and downloads go through the REST API. */
|
||||
export abstract class AttachmentsGateway {
|
||||
abstract upload(
|
||||
issueId: string,
|
||||
file: File,
|
||||
commentId?: string | null,
|
||||
): Observable<CommandResult>;
|
||||
/** The file's bytes, to show (images) or save. */
|
||||
abstract download(issueId: string, attachment: Attachment): Observable<Blob>;
|
||||
abstract remove(
|
||||
issueId: string,
|
||||
attachmentId: string,
|
||||
): Observable<CommandResult>;
|
||||
}
|
||||
|
||||
export abstract class ReleasesGateway {
|
||||
abstract list(projectId: string): Observable<Release[]>;
|
||||
/** Planned releases of all my projects, soonest target date first. */
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { HttpClient, HttpHeaders } from '@angular/common/http';
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import {
|
||||
AccessTokenSource,
|
||||
API_CONFIG,
|
||||
} from '@task-stream/web/shared/infrastructure';
|
||||
import {
|
||||
Attachment,
|
||||
AttachmentsGateway,
|
||||
CommandResult,
|
||||
} from '@task-stream/web/tracker/domain';
|
||||
import { from, Observable, switchMap } from 'rxjs';
|
||||
|
||||
/**
|
||||
* Files travel over REST (`/api/issues/:id/attachments`): GraphQL is not made
|
||||
* for bytes. The ticket's list of files comes with the ticket itself.
|
||||
*/
|
||||
@Injectable()
|
||||
export class HttpAttachmentsGateway extends AttachmentsGateway {
|
||||
private readonly http = inject(HttpClient);
|
||||
private readonly api = inject(API_CONFIG);
|
||||
private readonly tokens = inject(AccessTokenSource);
|
||||
|
||||
upload(
|
||||
issueId: string,
|
||||
file: File,
|
||||
commentId?: string | null,
|
||||
): Observable<CommandResult> {
|
||||
const body = new FormData();
|
||||
body.append('file', file, file.name);
|
||||
if (commentId) body.append('commentId', commentId);
|
||||
return this.authorized((headers) =>
|
||||
this.http.post<CommandResult>(this.url(issueId), body, { headers }),
|
||||
);
|
||||
}
|
||||
|
||||
download(issueId: string, attachment: Attachment): Observable<Blob> {
|
||||
return this.authorized((headers) =>
|
||||
this.http.get(this.url(issueId, attachment.id), {
|
||||
headers,
|
||||
responseType: 'blob',
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
remove(issueId: string, attachmentId: string): Observable<CommandResult> {
|
||||
return this.authorized((headers) =>
|
||||
this.http.delete<CommandResult>(this.url(issueId, attachmentId), {
|
||||
headers,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
private url(issueId: string, attachmentId?: string): string {
|
||||
const base = `${this.api.restUrl}/issues/${encodeURIComponent(issueId)}/attachments`;
|
||||
return attachmentId ? `${base}/${encodeURIComponent(attachmentId)}` : base;
|
||||
}
|
||||
|
||||
/** Public projects can be read without a session: no token, no header. */
|
||||
private authorized<T>(
|
||||
request: (headers: HttpHeaders) => Observable<T>,
|
||||
): Observable<T> {
|
||||
return from(this.tokens.accessToken()).pipe(
|
||||
switchMap((token) =>
|
||||
request(
|
||||
token
|
||||
? new HttpHeaders({ Authorization: `Bearer ${token}` })
|
||||
: new HttpHeaders(),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -88,6 +88,17 @@ fragment IssueFields on Issue {
|
||||
issueId
|
||||
issueKey
|
||||
}
|
||||
attachments {
|
||||
id
|
||||
fileName
|
||||
mimeType
|
||||
size
|
||||
uploadedAt
|
||||
commentId
|
||||
uploadedBy {
|
||||
...UserRefFields
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fragment CommentFields on Comment {
|
||||
|
||||
@@ -237,6 +237,15 @@ export type IssueFieldsFragment = {
|
||||
issueId: string;
|
||||
issueKey: string;
|
||||
}>;
|
||||
attachments: Array<{
|
||||
id: string;
|
||||
fileName: string;
|
||||
mimeType: string;
|
||||
size: number;
|
||||
uploadedAt: string;
|
||||
commentId: string | null;
|
||||
uploadedBy: { id: string; name: string };
|
||||
}>;
|
||||
assignee: { id: string; name: string } | null;
|
||||
release: { id: string; name: string } | null;
|
||||
};
|
||||
@@ -342,6 +351,15 @@ export type IssueQuery = {
|
||||
issueId: string;
|
||||
issueKey: string;
|
||||
}>;
|
||||
attachments: Array<{
|
||||
id: string;
|
||||
fileName: string;
|
||||
mimeType: string;
|
||||
size: number;
|
||||
uploadedAt: string;
|
||||
commentId: string | null;
|
||||
uploadedBy: { id: string; name: string };
|
||||
}>;
|
||||
assignee: { id: string; name: string } | null;
|
||||
release: { id: string; name: string } | null;
|
||||
};
|
||||
@@ -1294,6 +1312,34 @@ export const IssueFieldsFragmentDoc = {
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
kind: 'Field',
|
||||
name: { kind: 'Name', value: 'attachments' },
|
||||
selectionSet: {
|
||||
kind: 'SelectionSet',
|
||||
selections: [
|
||||
{ kind: 'Field', name: { kind: 'Name', value: 'id' } },
|
||||
{ kind: 'Field', name: { kind: 'Name', value: 'fileName' } },
|
||||
{ kind: 'Field', name: { kind: 'Name', value: 'mimeType' } },
|
||||
{ kind: 'Field', name: { kind: 'Name', value: 'size' } },
|
||||
{ kind: 'Field', name: { kind: 'Name', value: 'uploadedAt' } },
|
||||
{ kind: 'Field', name: { kind: 'Name', value: 'commentId' } },
|
||||
{
|
||||
kind: 'Field',
|
||||
name: { kind: 'Name', value: 'uploadedBy' },
|
||||
selectionSet: {
|
||||
kind: 'SelectionSet',
|
||||
selections: [
|
||||
{
|
||||
kind: 'FragmentSpread',
|
||||
name: { kind: 'Name', value: 'UserRefFields' },
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
@@ -1877,6 +1923,34 @@ export const IssueDocument = {
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
kind: 'Field',
|
||||
name: { kind: 'Name', value: 'attachments' },
|
||||
selectionSet: {
|
||||
kind: 'SelectionSet',
|
||||
selections: [
|
||||
{ kind: 'Field', name: { kind: 'Name', value: 'id' } },
|
||||
{ kind: 'Field', name: { kind: 'Name', value: 'fileName' } },
|
||||
{ kind: 'Field', name: { kind: 'Name', value: 'mimeType' } },
|
||||
{ kind: 'Field', name: { kind: 'Name', value: 'size' } },
|
||||
{ kind: 'Field', name: { kind: 'Name', value: 'uploadedAt' } },
|
||||
{ kind: 'Field', name: { kind: 'Name', value: 'commentId' } },
|
||||
{
|
||||
kind: 'Field',
|
||||
name: { kind: 'Name', value: 'uploadedBy' },
|
||||
selectionSet: {
|
||||
kind: 'SelectionSet',
|
||||
selections: [
|
||||
{
|
||||
kind: 'FragmentSpread',
|
||||
name: { kind: 'Name', value: 'UserRefFields' },
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
} from '@angular/core';
|
||||
import {
|
||||
ActivityGateway,
|
||||
AttachmentsGateway,
|
||||
CommentsGateway,
|
||||
IssuesGateway,
|
||||
ProjectsGateway,
|
||||
@@ -18,10 +19,11 @@ import {
|
||||
GraphqlUsersGateway,
|
||||
} from './adapters/graphql-collaboration.gateways';
|
||||
import { GraphqlIssuesGateway } from './adapters/graphql-issues.gateway';
|
||||
import { HttpAttachmentsGateway } from './adapters/http-attachments.gateway';
|
||||
import { GraphqlProjectsGateway } from './adapters/graphql-projects.gateway';
|
||||
import { GraphqlRealtimeGateway } from './adapters/graphql-realtime.gateway';
|
||||
|
||||
/** Ports → GraphQL adapters. */
|
||||
/** Ports → GraphQL adapters (and REST for files). */
|
||||
export function provideTrackerInfrastructure(): EnvironmentProviders {
|
||||
return makeEnvironmentProviders([
|
||||
{ provide: ProjectsGateway, useClass: GraphqlProjectsGateway },
|
||||
@@ -29,6 +31,7 @@ export function provideTrackerInfrastructure(): EnvironmentProviders {
|
||||
{ provide: CommentsGateway, useClass: GraphqlCommentsGateway },
|
||||
{ provide: ReleasesGateway, useClass: GraphqlReleasesGateway },
|
||||
{ provide: ActivityGateway, useClass: GraphqlActivityGateway },
|
||||
{ provide: AttachmentsGateway, useClass: HttpAttachmentsGateway },
|
||||
{ provide: UsersGateway, useClass: GraphqlUsersGateway },
|
||||
{ provide: TrackerRealtimeGateway, useClass: GraphqlRealtimeGateway },
|
||||
]);
|
||||
|
||||
@@ -338,3 +338,10 @@ a.ts-key {
|
||||
font-size: 0.8125rem;
|
||||
color: var(--ts-brand);
|
||||
}
|
||||
|
||||
.ts-attachments {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(16rem, 1fr));
|
||||
gap: 0.5rem;
|
||||
margin: 0.5rem 0;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
Component,
|
||||
computed,
|
||||
effect,
|
||||
HostListener,
|
||||
inject,
|
||||
input,
|
||||
signal,
|
||||
@@ -13,6 +14,7 @@ import { form, FormField, required } from '@angular/forms/signals';
|
||||
import { RouterLink } from '@angular/router';
|
||||
import {
|
||||
PiActionButtonComponent,
|
||||
PiFileUploadComponent,
|
||||
PiIconButtonComponent,
|
||||
PiIconComponent,
|
||||
PiLabelDirective,
|
||||
@@ -21,15 +23,17 @@ import {
|
||||
PiSkeletonComponent,
|
||||
PiTextareaComponent,
|
||||
PiTextFieldComponent,
|
||||
type PiFileRejection,
|
||||
type PiSelectFieldOption,
|
||||
} from '@pi/ui';
|
||||
import { DrawerService } from '@task-stream/web/shared/ui';
|
||||
import { DrawerService, ToastService } from '@task-stream/web/shared/ui';
|
||||
import {
|
||||
IssueFacade,
|
||||
ProjectFacade,
|
||||
provideIssueFacade,
|
||||
} from '@task-stream/web/tracker/application';
|
||||
import {
|
||||
Attachment,
|
||||
Comment,
|
||||
IssueLink,
|
||||
IssueLinkType,
|
||||
@@ -46,8 +50,11 @@ import {
|
||||
timeAgo,
|
||||
typeLook,
|
||||
} from '../ui/copy';
|
||||
import { AttachmentItem } from '../ui/attachments';
|
||||
|
||||
const NONE = '';
|
||||
/** Same ceiling as the API's ATTACHMENTS_MAX_MB default. */
|
||||
const MAX_FILE_BYTES = 25 * 1024 * 1024;
|
||||
|
||||
@Component({
|
||||
selector: 'ts-issue-page',
|
||||
@@ -55,7 +62,9 @@ const NONE = '';
|
||||
imports: [
|
||||
RouterLink,
|
||||
FormField,
|
||||
AttachmentItem,
|
||||
PiActionButtonComponent,
|
||||
PiFileUploadComponent,
|
||||
PiIconComponent,
|
||||
PiIconButtonComponent,
|
||||
PiLabelDirective,
|
||||
@@ -134,6 +143,47 @@ const NONE = '';
|
||||
}
|
||||
</article>
|
||||
|
||||
<article class="ts-block">
|
||||
<h2 class="ts-section">
|
||||
Adjuntos
|
||||
<span class="ts-mono">{{ ticketFiles().length }}</span>
|
||||
</h2>
|
||||
@if (ticketFiles().length) {
|
||||
<div class="ts-attachments">
|
||||
@for (file of ticketFiles(); track file.id) {
|
||||
<ts-attachment
|
||||
[attachment]="file"
|
||||
[removable]="canRemove(file)"
|
||||
/>
|
||||
}
|
||||
</div>
|
||||
} @else if (!project.canContribute()) {
|
||||
<p class="ts-muted">Sin adjuntos.</p>
|
||||
}
|
||||
@if (project.canContribute()) {
|
||||
<div class="ts-form">
|
||||
<pi-file-upload
|
||||
label="Capturas, logs, vídeos…"
|
||||
hint="Arrastra aquí, elige, o pega una captura con Ctrl+V. Hasta 25 MB por archivo."
|
||||
[multiple]="true"
|
||||
[maxFiles]="10"
|
||||
[maxSizeBytes]="maxFileBytes"
|
||||
[(value)]="pendingFiles"
|
||||
(rejected)="rejected($event)"
|
||||
/>
|
||||
@if (pendingFiles().length) {
|
||||
<div>
|
||||
<pi-action-button
|
||||
color="primary"
|
||||
[text]="'Adjuntar ' + pendingFiles().length"
|
||||
(execute)="attach()"
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</article>
|
||||
|
||||
<article class="ts-block">
|
||||
<h2 class="ts-section">Relaciones</h2>
|
||||
@for (
|
||||
@@ -238,6 +288,16 @@ const NONE = '';
|
||||
}
|
||||
</div>
|
||||
<p class="ts-prewrap">{{ comment.body }}</p>
|
||||
@if (filesOf(comment).length) {
|
||||
<div class="ts-attachments">
|
||||
@for (file of filesOf(comment); track file.id) {
|
||||
<ts-attachment
|
||||
[attachment]="file"
|
||||
[removable]="canRemove(file)"
|
||||
/>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@@ -251,6 +311,14 @@ const NONE = '';
|
||||
placeholder="Deja una decisión, una explicación, un paso para reproducir…"
|
||||
[(value)]="commentBody"
|
||||
/>
|
||||
<pi-file-upload
|
||||
label="Adjuntar al comentario"
|
||||
[multiple]="true"
|
||||
[maxFiles]="10"
|
||||
[maxSizeBytes]="maxFileBytes"
|
||||
[(value)]="commentFiles"
|
||||
(rejected)="rejected($event)"
|
||||
/>
|
||||
<div>
|
||||
<pi-action-button
|
||||
color="primary"
|
||||
@@ -436,6 +504,7 @@ export class IssuePage {
|
||||
protected readonly facade = inject(IssueFacade);
|
||||
protected readonly project = inject(ProjectFacade);
|
||||
private readonly drawer = inject(DrawerService);
|
||||
private readonly toast = inject(ToastService);
|
||||
private readonly reasonForm =
|
||||
viewChild.required<TemplateRef<unknown>>('reasonForm');
|
||||
private readonly editForm =
|
||||
@@ -506,6 +575,21 @@ export class IssuePage {
|
||||
protected readonly linkType = signal<string | null>(IssueLinkType.RELATES_TO);
|
||||
protected readonly linkTarget = signal('');
|
||||
protected readonly commentBody = signal('');
|
||||
protected readonly commentFiles = signal<File[]>([]);
|
||||
protected readonly pendingFiles = signal<File[]>([]);
|
||||
protected readonly maxFileBytes = MAX_FILE_BYTES;
|
||||
|
||||
/** Files on the ticket itself; those under a comment are shown there. */
|
||||
protected readonly ticketFiles = computed(
|
||||
() => this.facade.issue()?.attachments.filter((a) => !a.commentId) ?? [],
|
||||
);
|
||||
protected filesOf = (comment: Comment): Attachment[] =>
|
||||
this.facade
|
||||
.issue()
|
||||
?.attachments.filter((a) => a.commentId === comment.id) ?? [];
|
||||
protected canRemove = (file: Attachment): boolean =>
|
||||
this.project.canContribute() &&
|
||||
(file.uploadedBy.id === this.facade.me() || this.project.canManage());
|
||||
|
||||
private pendingStatus: string | null = null;
|
||||
private readonly reasonModel = signal({ text: '' });
|
||||
@@ -590,8 +674,53 @@ export class IssuePage {
|
||||
protected addComment(): void {
|
||||
const body = this.commentBody().trim();
|
||||
if (!body) return;
|
||||
this.facade.addComment(body);
|
||||
this.facade.addComment(body, this.commentFiles());
|
||||
this.commentBody.set('');
|
||||
this.commentFiles.set([]);
|
||||
}
|
||||
|
||||
protected attach(): void {
|
||||
this.facade.attach(this.pendingFiles());
|
||||
this.pendingFiles.set([]);
|
||||
}
|
||||
|
||||
protected rejected(rejections: PiFileRejection[]): void {
|
||||
for (const { file, reason } of rejections) {
|
||||
this.toast.error(
|
||||
reason === 'size'
|
||||
? `${file.name} pasa de 25 MB`
|
||||
: reason === 'max-files'
|
||||
? 'Como mucho 10 archivos a la vez'
|
||||
: `${file.name} no es un tipo admitido`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** A screenshot pasted anywhere on the ticket is attached to it. */
|
||||
@HostListener('document:paste', ['$event'])
|
||||
protected pasted(event: ClipboardEvent): void {
|
||||
const target = event.target as HTMLElement | null;
|
||||
// Pasting text into a field is just typing.
|
||||
if (target?.closest('input, textarea, [contenteditable]')) return;
|
||||
if (!this.project.canContribute() || !this.facade.issue()) return;
|
||||
const files = [...(event.clipboardData?.files ?? [])].filter(
|
||||
(file) => file.size <= MAX_FILE_BYTES,
|
||||
);
|
||||
if (!files.length) return;
|
||||
event.preventDefault();
|
||||
this.facade.attach(
|
||||
files.map((file) =>
|
||||
file.name && file.name !== 'image.png'
|
||||
? file
|
||||
: new File(
|
||||
[file],
|
||||
`captura-${new Date().toISOString().slice(0, 19).replace(/[:T]/g, '-')}.png`,
|
||||
{
|
||||
type: file.type,
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
protected openEditComment(comment: Comment): void {
|
||||
|
||||
178
libs/web/tracker/presenters/src/lib/ui/attachments.ts
Normal file
178
libs/web/tracker/presenters/src/lib/ui/attachments.ts
Normal file
@@ -0,0 +1,178 @@
|
||||
import {
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
DestroyRef,
|
||||
computed,
|
||||
inject,
|
||||
input,
|
||||
OnInit,
|
||||
signal,
|
||||
} from '@angular/core';
|
||||
import { PiIconButtonComponent, PiIconComponent } from '@pi/ui';
|
||||
import { IssueFacade } from '@task-stream/web/tracker/application';
|
||||
import { Attachment } from '@task-stream/web/tracker/domain';
|
||||
import { timeAgo } from './copy';
|
||||
|
||||
/** Types the browser shows in a tab of its own; anything else is saved. */
|
||||
const OPENS_IN_TAB =
|
||||
/^(image\/(png|jpe?g|gif|webp|avif)|video\/(mp4|webm)|audio\/(mpeg|ogg|wav)|application\/pdf|text\/plain)$/;
|
||||
const PREVIEWED = /^image\/(png|jpe?g|gif|webp|avif)$/;
|
||||
|
||||
export function readableSize(bytes: number): string {
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;
|
||||
return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
/**
|
||||
* One file: a thumbnail for images, an icon otherwise. The bytes are fetched
|
||||
* with the session's token (a plain link could not send it) and shown from a
|
||||
* local object URL, released when the item goes.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'ts-attachment',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
imports: [PiIconComponent, PiIconButtonComponent],
|
||||
template: `
|
||||
<button
|
||||
type="button"
|
||||
class="ts-attachment__open"
|
||||
[attr.aria-label]="'Abrir ' + attachment().fileName"
|
||||
(click)="open()"
|
||||
>
|
||||
@if (thumbnail(); as src) {
|
||||
<img class="ts-attachment__thumb" [src]="src" alt="" />
|
||||
} @else {
|
||||
<span class="ts-attachment__icon" aria-hidden="true">
|
||||
<pi-icon [icon]="isImage() ? 'image' : 'document'" size="small" />
|
||||
</span>
|
||||
}
|
||||
<span class="ts-attachment__text">
|
||||
<span class="ts-attachment__name">{{ attachment().fileName }}</span>
|
||||
<span class="ts-attachment__meta"
|
||||
>{{ size() }} · {{ attachment().uploadedBy.name }} ·
|
||||
{{ ago(attachment().uploadedAt) }}</span
|
||||
>
|
||||
</span>
|
||||
</button>
|
||||
@if (removable()) {
|
||||
<pi-icon-button
|
||||
icon="trash"
|
||||
color="grey"
|
||||
appearance="ghost"
|
||||
[attr.aria-label]="'Quitar ' + attachment().fileName"
|
||||
(execute)="remove()"
|
||||
/>
|
||||
}
|
||||
`,
|
||||
styles: `
|
||||
:host {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
min-width: 0;
|
||||
}
|
||||
.ts-attachment__open {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
padding: 0.375rem;
|
||||
border: 1px solid var(--ts-line, rgba(127, 127, 127, 0.25));
|
||||
border-radius: 0.5rem;
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
.ts-attachment__open:hover,
|
||||
.ts-attachment__open:focus-visible {
|
||||
border-color: currentColor;
|
||||
}
|
||||
.ts-attachment__thumb,
|
||||
.ts-attachment__icon {
|
||||
flex: none;
|
||||
width: 3rem;
|
||||
height: 3rem;
|
||||
border-radius: 0.375rem;
|
||||
object-fit: cover;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
background: rgba(127, 127, 127, 0.12);
|
||||
}
|
||||
.ts-attachment__text {
|
||||
display: grid;
|
||||
min-width: 0;
|
||||
}
|
||||
.ts-attachment__name {
|
||||
font-weight: 600;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.ts-attachment__meta {
|
||||
font-size: 0.8125rem;
|
||||
opacity: 0.7;
|
||||
}
|
||||
`,
|
||||
})
|
||||
export class AttachmentItem implements OnInit {
|
||||
readonly attachment = input.required<Attachment>();
|
||||
readonly removable = input(false);
|
||||
|
||||
private readonly facade = inject(IssueFacade);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
private objectUrl: string | null = null;
|
||||
|
||||
protected readonly thumbnail = signal<string | null>(null);
|
||||
protected readonly isImage = computed(() =>
|
||||
PREVIEWED.test(this.attachment().mimeType),
|
||||
);
|
||||
protected readonly size = computed(() =>
|
||||
readableSize(this.attachment().size),
|
||||
);
|
||||
protected readonly ago = timeAgo;
|
||||
|
||||
ngOnInit(): void {
|
||||
this.destroyRef.onDestroy(() => {
|
||||
if (this.objectUrl) URL.revokeObjectURL(this.objectUrl);
|
||||
});
|
||||
// Small images only: a 20 MB screenshot is not worth a thumbnail.
|
||||
if (this.isImage() && this.attachment().size <= 5 * 1024 * 1024) {
|
||||
this.withUrl((url) => this.thumbnail.set(url));
|
||||
}
|
||||
}
|
||||
|
||||
protected open(): void {
|
||||
this.withUrl((url) => {
|
||||
const { fileName, mimeType } = this.attachment();
|
||||
if (OPENS_IN_TAB.test(mimeType)) {
|
||||
window.open(url, '_blank', 'noopener');
|
||||
return;
|
||||
}
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = fileName;
|
||||
link.click();
|
||||
});
|
||||
}
|
||||
|
||||
protected remove(): void {
|
||||
if (confirm(`¿Quitar ${this.attachment().fileName}?`)) {
|
||||
this.facade.removeAttachment(this.attachment().id);
|
||||
}
|
||||
}
|
||||
|
||||
private withUrl(use: (url: string) => void): void {
|
||||
if (this.objectUrl) {
|
||||
use(this.objectUrl);
|
||||
return;
|
||||
}
|
||||
this.facade.fileOf(this.attachment()).subscribe((blob) => {
|
||||
this.objectUrl = URL.createObjectURL(blob);
|
||||
use(this.objectUrl);
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user