mirror of
https://github.com/felipegcoutinho/openmonetis.git
synced 2026-07-09 03:16:01 +00:00
feat(anotações): permite anexos em notas
This commit is contained in:
9
drizzle/0031_lame_cerise.sql
Normal file
9
drizzle/0031_lame_cerise.sql
Normal file
@@ -0,0 +1,9 @@
|
||||
CREATE TABLE "anotacao_anexos" (
|
||||
"anotacao_id" uuid NOT NULL,
|
||||
"anexo_id" uuid NOT NULL,
|
||||
CONSTRAINT "anotacao_anexos_anotacao_id_anexo_id_pk" PRIMARY KEY("anotacao_id","anexo_id")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "anotacao_anexos" ADD CONSTRAINT "anotacao_anexos_anotacao_id_anotacoes_id_fk" FOREIGN KEY ("anotacao_id") REFERENCES "public"."anotacoes"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "anotacao_anexos" ADD CONSTRAINT "anotacao_anexos_anexo_id_anexos_id_fk" FOREIGN KEY ("anexo_id") REFERENCES "public"."anexos"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
CREATE INDEX "anotacao_anexos_anexo_id_idx" ON "anotacao_anexos" USING btree ("anexo_id");
|
||||
2988
drizzle/meta/0031_snapshot.json
Normal file
2988
drizzle/meta/0031_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
@@ -211,6 +211,13 @@
|
||||
"when": 1780150535055,
|
||||
"tag": "0030_complete_umar",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 31,
|
||||
"version": "7",
|
||||
"when": 1782051007412,
|
||||
"tag": "0031_lame_cerise",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,16 +1,24 @@
|
||||
import { connection } from "next/server";
|
||||
import { NotesPage } from "@/features/notes/components/notes-page";
|
||||
import { fetchAllNotesForUser } from "@/features/notes/queries";
|
||||
import { fetchUserPreferences } from "@/features/settings/queries";
|
||||
import { getUserId } from "@/shared/lib/auth/server";
|
||||
|
||||
export default async function Page() {
|
||||
await connection();
|
||||
const userId = await getUserId();
|
||||
const { activeNotes, archivedNotes } = await fetchAllNotesForUser(userId);
|
||||
const [{ activeNotes, archivedNotes }, preferences] = await Promise.all([
|
||||
fetchAllNotesForUser(userId),
|
||||
fetchUserPreferences(userId),
|
||||
]);
|
||||
|
||||
return (
|
||||
<main className="flex flex-col gap-6">
|
||||
<NotesPage notes={activeNotes} archivedNotes={archivedNotes} />
|
||||
<NotesPage
|
||||
notes={activeNotes}
|
||||
archivedNotes={archivedNotes}
|
||||
attachmentMaxSizeMb={preferences?.attachmentMaxSizeMb ?? 50}
|
||||
/>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -847,11 +847,12 @@ export const budgetsRelations = relations(budgets, ({ one }) => ({
|
||||
}),
|
||||
}));
|
||||
|
||||
export const notesRelations = relations(notes, ({ one }) => ({
|
||||
export const notesRelations = relations(notes, ({ one, many }) => ({
|
||||
user: one(user, {
|
||||
fields: [notes.userId],
|
||||
references: [user.id],
|
||||
}),
|
||||
noteAttachments: many(noteAttachments),
|
||||
}));
|
||||
|
||||
export const savedInsightsRelations = relations(savedInsights, ({ one }) => ({
|
||||
@@ -972,6 +973,24 @@ export const transactionAttachments = pgTable(
|
||||
}),
|
||||
);
|
||||
|
||||
export const noteAttachments = pgTable(
|
||||
"anotacao_anexos",
|
||||
{
|
||||
noteId: uuid("anotacao_id")
|
||||
.notNull()
|
||||
.references(() => notes.id, { onDelete: "cascade" }),
|
||||
attachmentId: uuid("anexo_id")
|
||||
.notNull()
|
||||
.references(() => attachments.id, { onDelete: "cascade" }),
|
||||
},
|
||||
(table) => ({
|
||||
pk: primaryKey({ columns: [table.noteId, table.attachmentId] }),
|
||||
attachmentIdIdx: index("anotacao_anexos_anexo_id_idx").on(
|
||||
table.attachmentId,
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
export const importCategoryMappings = pgTable(
|
||||
"import_category_mappings",
|
||||
{
|
||||
@@ -1044,6 +1063,7 @@ export const attachmentsRelations = relations(attachments, ({ one, many }) => ({
|
||||
references: [user.id],
|
||||
}),
|
||||
transactionAttachments: many(transactionAttachments),
|
||||
noteAttachments: many(noteAttachments),
|
||||
}));
|
||||
|
||||
export const transactionAttachmentsRelations = relations(
|
||||
@@ -1060,8 +1080,23 @@ export const transactionAttachmentsRelations = relations(
|
||||
}),
|
||||
);
|
||||
|
||||
export const noteAttachmentsRelations = relations(
|
||||
noteAttachments,
|
||||
({ one }) => ({
|
||||
note: one(notes, {
|
||||
fields: [noteAttachments.noteId],
|
||||
references: [notes.id],
|
||||
}),
|
||||
attachment: one(attachments, {
|
||||
fields: [noteAttachments.attachmentId],
|
||||
references: [attachments.id],
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
export type Attachment = typeof attachments.$inferSelect;
|
||||
export type TransactionAttachment = typeof transactionAttachments.$inferSelect;
|
||||
export type NoteAttachment = typeof noteAttachments.$inferSelect;
|
||||
|
||||
export const establishmentLogosRelations = relations(
|
||||
establishmentLogos,
|
||||
|
||||
@@ -9,6 +9,7 @@ const mapDashboardNoteToNote = (note: DashboardNote): Note => ({
|
||||
tasks: note.tasks,
|
||||
archived: note.archived,
|
||||
createdAt: note.createdAt,
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
export const mapDashboardNotesToNotes = (notes: DashboardNote[]) =>
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"use server";
|
||||
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { and, eq, inArray } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { notes } from "@/db/schema";
|
||||
import { attachments, noteAttachments, notes } from "@/db/schema";
|
||||
import {
|
||||
handleActionError,
|
||||
revalidateForEntity,
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
import { getUser } from "@/shared/lib/auth/server";
|
||||
import { db } from "@/shared/lib/db";
|
||||
import { uuidSchema } from "@/shared/lib/schemas/common";
|
||||
import { deleteS3Object } from "@/shared/lib/storage/presign";
|
||||
import type { ActionResult } from "@/shared/lib/types/actions";
|
||||
|
||||
const taskSchema = z.object({
|
||||
@@ -70,25 +71,42 @@ type NoteDeleteInput = z.infer<typeof deleteNoteSchema>;
|
||||
|
||||
export async function createNoteAction(
|
||||
input: NoteCreateInput,
|
||||
): Promise<ActionResult> {
|
||||
): Promise<ActionResult<{ noteId: string }>> {
|
||||
try {
|
||||
const user = await getUser();
|
||||
const data = createNoteSchema.parse(input);
|
||||
|
||||
await db.insert(notes).values({
|
||||
title: data.title,
|
||||
description: data.description,
|
||||
type: data.type,
|
||||
tasks:
|
||||
data.tasks && data.tasks.length > 0 ? JSON.stringify(data.tasks) : null,
|
||||
userId: user.id,
|
||||
});
|
||||
const [created] = await db
|
||||
.insert(notes)
|
||||
.values({
|
||||
title: data.title,
|
||||
description: data.description,
|
||||
type: data.type,
|
||||
tasks:
|
||||
data.tasks && data.tasks.length > 0
|
||||
? JSON.stringify(data.tasks)
|
||||
: null,
|
||||
userId: user.id,
|
||||
})
|
||||
.returning({ id: notes.id });
|
||||
|
||||
if (!created) {
|
||||
return { success: false, error: "Não foi possível criar a anotação." };
|
||||
}
|
||||
|
||||
revalidateForEntity("notes", user.id);
|
||||
|
||||
return { success: true, message: "Anotação criada com sucesso." };
|
||||
return {
|
||||
success: true,
|
||||
message: "Anotação criada com sucesso.",
|
||||
data: { noteId: created.id },
|
||||
};
|
||||
} catch (error) {
|
||||
return handleActionError(error);
|
||||
const result = handleActionError(error);
|
||||
return {
|
||||
success: false,
|
||||
error: result.success ? "Ocorreu um erro inesperado." : result.error,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -135,6 +153,25 @@ export async function deleteNoteAction(
|
||||
const user = await getUser();
|
||||
const data = deleteNoteSchema.parse(input);
|
||||
|
||||
const linkedAttachments = await db
|
||||
.select({ id: attachments.id, fileKey: attachments.fileKey })
|
||||
.from(noteAttachments)
|
||||
.innerJoin(
|
||||
attachments,
|
||||
and(
|
||||
eq(noteAttachments.attachmentId, attachments.id),
|
||||
eq(attachments.userId, user.id),
|
||||
),
|
||||
)
|
||||
.innerJoin(
|
||||
notes,
|
||||
and(
|
||||
eq(noteAttachments.noteId, notes.id),
|
||||
eq(notes.id, data.id),
|
||||
eq(notes.userId, user.id),
|
||||
),
|
||||
);
|
||||
|
||||
const [deleted] = await db
|
||||
.delete(notes)
|
||||
.where(and(eq(notes.id, data.id), eq(notes.userId, user.id)))
|
||||
@@ -147,6 +184,23 @@ export async function deleteNoteAction(
|
||||
};
|
||||
}
|
||||
|
||||
if (linkedAttachments.length > 0) {
|
||||
await Promise.all(
|
||||
linkedAttachments.map((attachment) =>
|
||||
deleteS3Object(attachment.fileKey),
|
||||
),
|
||||
);
|
||||
await db.delete(attachments).where(
|
||||
and(
|
||||
eq(attachments.userId, user.id),
|
||||
inArray(
|
||||
attachments.id,
|
||||
linkedAttachments.map((attachment) => attachment.id),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
revalidateForEntity("notes", user.id);
|
||||
|
||||
return { success: true, message: "Anotação removida com sucesso." };
|
||||
|
||||
279
src/features/notes/actions/attachments.ts
Normal file
279
src/features/notes/actions/attachments.ts
Normal file
@@ -0,0 +1,279 @@
|
||||
"use server";
|
||||
|
||||
import crypto, { randomUUID } from "node:crypto";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { z } from "zod/v4";
|
||||
import {
|
||||
attachments,
|
||||
noteAttachments,
|
||||
notes,
|
||||
userPreferences,
|
||||
} from "@/db/schema";
|
||||
import {
|
||||
handleActionError,
|
||||
revalidateForEntity,
|
||||
} from "@/shared/lib/actions/helpers";
|
||||
import {
|
||||
ALLOWED_MIME_TYPES,
|
||||
ATTACHMENT_SIZE_OPTIONS,
|
||||
} from "@/shared/lib/attachments/config";
|
||||
import { getUser } from "@/shared/lib/auth/server";
|
||||
import { db } from "@/shared/lib/db";
|
||||
import {
|
||||
createPresignedPutUrl,
|
||||
deleteS3Object,
|
||||
headS3Object,
|
||||
} from "@/shared/lib/storage/presign";
|
||||
import type { ActionResult } from "@/shared/lib/types/actions";
|
||||
|
||||
const UPLOAD_TOKEN_EXPIRY_SECONDS = 10 * 60;
|
||||
const MAX_NOTE_FILE_SIZE = Math.max(...ATTACHMENT_SIZE_OPTIONS) * 1024 * 1024;
|
||||
|
||||
const presignSchema = z.object({
|
||||
noteId: z.string().uuid(),
|
||||
fileName: z.string().min(1).max(255),
|
||||
mimeType: z.enum(ALLOWED_MIME_TYPES),
|
||||
fileSize: z.number().positive().max(MAX_NOTE_FILE_SIZE),
|
||||
});
|
||||
|
||||
const tokenPayloadSchema = presignSchema.extend({
|
||||
userId: z.string().min(1),
|
||||
fileKey: z.string().min(1),
|
||||
exp: z.number().int(),
|
||||
});
|
||||
|
||||
type UploadTokenPayload = z.infer<typeof tokenPayloadSchema>;
|
||||
|
||||
type PresignResult =
|
||||
| { success: true; presignedUrl: string; uploadToken: string }
|
||||
| { success: false; error: string };
|
||||
|
||||
export type NoteAttachmentData = {
|
||||
attachmentId: string;
|
||||
fileName: string;
|
||||
fileSize: number;
|
||||
mimeType: string;
|
||||
};
|
||||
|
||||
function getUploadTokenSecret(): string {
|
||||
const secret = process.env.BETTER_AUTH_SECRET;
|
||||
if (!secret) throw new Error("BETTER_AUTH_SECRET is required.");
|
||||
return secret;
|
||||
}
|
||||
|
||||
function encode(value: string): string {
|
||||
return Buffer.from(value).toString("base64url");
|
||||
}
|
||||
|
||||
function signUploadToken(payload: UploadTokenPayload): string {
|
||||
const encoded = encode(JSON.stringify(payload));
|
||||
const signature = crypto
|
||||
.createHmac("sha256", getUploadTokenSecret())
|
||||
.update(encoded)
|
||||
.digest("base64url");
|
||||
return `${encoded}.${signature}`;
|
||||
}
|
||||
|
||||
function verifyUploadToken(token: string): UploadTokenPayload | null {
|
||||
try {
|
||||
const [encoded, signature] = token.split(".");
|
||||
if (!encoded || !signature) return null;
|
||||
const expected = crypto
|
||||
.createHmac("sha256", getUploadTokenSecret())
|
||||
.update(encoded)
|
||||
.digest("base64url");
|
||||
if (
|
||||
signature.length !== expected.length ||
|
||||
!crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected))
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const parsed = tokenPayloadSchema.safeParse(
|
||||
JSON.parse(Buffer.from(encoded, "base64url").toString("utf8")),
|
||||
);
|
||||
if (!parsed.success || parsed.data.exp < Math.floor(Date.now() / 1000)) {
|
||||
return null;
|
||||
}
|
||||
if (!parsed.data.fileKey.startsWith(`${parsed.data.userId}/`)) return null;
|
||||
return parsed.data;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function findOwnedNote(noteId: string, userId: string) {
|
||||
const [note] = await db
|
||||
.select({ id: notes.id, type: notes.type })
|
||||
.from(notes)
|
||||
.where(and(eq(notes.id, noteId), eq(notes.userId, userId)));
|
||||
return note?.type === "nota" ? note : null;
|
||||
}
|
||||
|
||||
async function getAttachmentLimitBytes(userId: string): Promise<number> {
|
||||
const [preferences] = await db
|
||||
.select({ maxSizeMb: userPreferences.attachmentMaxSizeMb })
|
||||
.from(userPreferences)
|
||||
.where(eq(userPreferences.userId, userId));
|
||||
return (preferences?.maxSizeMb ?? 50) * 1024 * 1024;
|
||||
}
|
||||
|
||||
export async function getPresignedNoteAttachmentUploadUrlAction(input: {
|
||||
noteId: string;
|
||||
fileName: string;
|
||||
mimeType: string;
|
||||
fileSize: number;
|
||||
}): Promise<PresignResult> {
|
||||
try {
|
||||
const user = await getUser();
|
||||
const data = presignSchema.parse(input);
|
||||
if (data.fileSize > (await getAttachmentLimitBytes(user.id))) {
|
||||
return {
|
||||
success: false,
|
||||
error: "O arquivo excede o limite configurado para anexos.",
|
||||
};
|
||||
}
|
||||
if (!(await findOwnedNote(data.noteId, user.id))) {
|
||||
return { success: false, error: "Nota não encontrada." };
|
||||
}
|
||||
|
||||
const extensions: Record<(typeof ALLOWED_MIME_TYPES)[number], string> = {
|
||||
"application/pdf": "pdf",
|
||||
"image/jpeg": "jpg",
|
||||
"image/png": "png",
|
||||
"image/webp": "webp",
|
||||
};
|
||||
const extension = extensions[data.mimeType];
|
||||
const fileKey = `${user.id}/${randomUUID()}.${extension}`;
|
||||
const presignedUrl = await createPresignedPutUrl(fileKey, data.mimeType);
|
||||
const uploadToken = signUploadToken({
|
||||
...data,
|
||||
userId: user.id,
|
||||
fileKey,
|
||||
exp: Math.floor(Date.now() / 1000) + UPLOAD_TOKEN_EXPIRY_SECONDS,
|
||||
});
|
||||
return { success: true, presignedUrl, uploadToken };
|
||||
} catch (error) {
|
||||
const result = handleActionError(error);
|
||||
return {
|
||||
success: false,
|
||||
error: result.success ? "Algo deu errado." : result.error,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export async function confirmNoteAttachmentUploadAction(input: {
|
||||
uploadToken: string;
|
||||
}): Promise<ActionResult<NoteAttachmentData>> {
|
||||
try {
|
||||
const user = await getUser();
|
||||
const payload = verifyUploadToken(input.uploadToken);
|
||||
if (!payload || payload.userId !== user.id) {
|
||||
return { success: false, error: "Upload de anexo inválido ou expirado." };
|
||||
}
|
||||
if (!(await findOwnedNote(payload.noteId, user.id))) {
|
||||
return { success: false, error: "Nota não encontrada." };
|
||||
}
|
||||
|
||||
const metadata = await headS3Object(payload.fileKey);
|
||||
if (
|
||||
!metadata.contentLength ||
|
||||
metadata.contentLength !== payload.fileSize ||
|
||||
metadata.contentLength > MAX_NOTE_FILE_SIZE ||
|
||||
metadata.contentType !== payload.mimeType
|
||||
) {
|
||||
return {
|
||||
success: false,
|
||||
error: "O arquivo enviado não confere com o upload autorizado.",
|
||||
};
|
||||
}
|
||||
|
||||
const [attachment] = await db
|
||||
.insert(attachments)
|
||||
.values({
|
||||
userId: user.id,
|
||||
fileKey: payload.fileKey,
|
||||
fileName: payload.fileName,
|
||||
fileSize: payload.fileSize,
|
||||
mimeType: payload.mimeType,
|
||||
})
|
||||
.returning({ id: attachments.id });
|
||||
if (!attachment)
|
||||
return { success: false, error: "Não foi possível salvar o anexo." };
|
||||
|
||||
await db.insert(noteAttachments).values({
|
||||
noteId: payload.noteId,
|
||||
attachmentId: attachment.id,
|
||||
});
|
||||
revalidateForEntity("notes", user.id);
|
||||
return {
|
||||
success: true,
|
||||
message: "Anexo enviado.",
|
||||
data: {
|
||||
attachmentId: attachment.id,
|
||||
fileName: payload.fileName,
|
||||
fileSize: payload.fileSize,
|
||||
mimeType: payload.mimeType,
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
const result = handleActionError(error);
|
||||
return {
|
||||
success: false,
|
||||
error: result.success ? "Ocorreu um erro inesperado." : result.error,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export async function removeNoteAttachmentAction(input: {
|
||||
noteId: string;
|
||||
attachmentId: string;
|
||||
}): Promise<ActionResult> {
|
||||
try {
|
||||
const user = await getUser();
|
||||
const data = z
|
||||
.object({ noteId: z.string().uuid(), attachmentId: z.string().uuid() })
|
||||
.parse(input);
|
||||
if (!(await findOwnedNote(data.noteId, user.id))) {
|
||||
return { success: false, error: "Nota não encontrada." };
|
||||
}
|
||||
const [attachment] = await db
|
||||
.select({ fileKey: attachments.fileKey })
|
||||
.from(noteAttachments)
|
||||
.innerJoin(
|
||||
attachments,
|
||||
and(
|
||||
eq(noteAttachments.attachmentId, attachments.id),
|
||||
eq(attachments.userId, user.id),
|
||||
),
|
||||
)
|
||||
.where(
|
||||
and(
|
||||
eq(noteAttachments.noteId, data.noteId),
|
||||
eq(noteAttachments.attachmentId, data.attachmentId),
|
||||
),
|
||||
);
|
||||
if (!attachment) return { success: false, error: "Anexo não encontrado." };
|
||||
|
||||
await db
|
||||
.delete(noteAttachments)
|
||||
.where(
|
||||
and(
|
||||
eq(noteAttachments.noteId, data.noteId),
|
||||
eq(noteAttachments.attachmentId, data.attachmentId),
|
||||
),
|
||||
);
|
||||
await deleteS3Object(attachment.fileKey);
|
||||
await db
|
||||
.delete(attachments)
|
||||
.where(
|
||||
and(
|
||||
eq(attachments.id, data.attachmentId),
|
||||
eq(attachments.userId, user.id),
|
||||
),
|
||||
);
|
||||
revalidateForEntity("notes", user.id);
|
||||
return { success: true, message: "Anexo removido." };
|
||||
} catch (error) {
|
||||
return handleActionError(error);
|
||||
}
|
||||
}
|
||||
345
src/features/notes/components/note-attachments-field.tsx
Normal file
345
src/features/notes/components/note-attachments-field.tsx
Normal file
@@ -0,0 +1,345 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
RiAttachment2,
|
||||
RiCloseLine,
|
||||
RiDeleteBinLine,
|
||||
RiDownloadLine,
|
||||
RiFileImageLine,
|
||||
RiFilePdf2Line,
|
||||
} from "@remixicon/react";
|
||||
import { useRef, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
confirmNoteAttachmentUploadAction,
|
||||
getPresignedNoteAttachmentUploadUrlAction,
|
||||
removeNoteAttachmentAction,
|
||||
} from "@/features/notes/actions/attachments";
|
||||
import type { NoteAttachment } from "@/features/notes/components/types";
|
||||
import { Button } from "@/shared/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/shared/components/ui/dialog";
|
||||
import {
|
||||
ALLOWED_MIME_TYPES,
|
||||
DEFAULT_MAX_FILE_SIZE_MB,
|
||||
} from "@/shared/lib/attachments/config";
|
||||
|
||||
type UploadResult =
|
||||
| { success: true; attachment: NoteAttachment }
|
||||
| { success: false; error: string };
|
||||
|
||||
export async function uploadNoteAttachment(
|
||||
noteId: string,
|
||||
file: File,
|
||||
): Promise<UploadResult> {
|
||||
try {
|
||||
const presign = await getPresignedNoteAttachmentUploadUrlAction({
|
||||
noteId,
|
||||
fileName: file.name,
|
||||
fileSize: file.size,
|
||||
mimeType: file.type,
|
||||
});
|
||||
if (!presign.success) return presign;
|
||||
|
||||
const uploaded = await fetch(presign.presignedUrl, {
|
||||
method: "PUT",
|
||||
body: file,
|
||||
headers: { "Content-Type": file.type },
|
||||
});
|
||||
if (!uploaded.ok) {
|
||||
return { success: false, error: "Não foi possível enviar o arquivo." };
|
||||
}
|
||||
|
||||
const confirmed = await confirmNoteAttachmentUploadAction({
|
||||
uploadToken: presign.uploadToken,
|
||||
});
|
||||
if (!confirmed.success || !confirmed.data) {
|
||||
return {
|
||||
success: false,
|
||||
error: confirmed.success
|
||||
? "Não foi possível salvar o anexo."
|
||||
: confirmed.error,
|
||||
};
|
||||
}
|
||||
return { success: true, attachment: confirmed.data };
|
||||
} catch {
|
||||
return {
|
||||
success: false,
|
||||
error: "Não foi possível enviar o arquivo agora.",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
||||
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
function validateFile(file: File, maxSizeMb: number): string | null {
|
||||
if (
|
||||
!ALLOWED_MIME_TYPES.includes(
|
||||
file.type as (typeof ALLOWED_MIME_TYPES)[number],
|
||||
)
|
||||
) {
|
||||
return "Tipo não suportado. Use PDF, JPEG, PNG ou WebP.";
|
||||
}
|
||||
if (file.size > maxSizeMb * 1024 * 1024) {
|
||||
return `O arquivo deve ter no máximo ${maxSizeMb}MB.`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
interface NoteAttachmentsFieldProps {
|
||||
noteId?: string;
|
||||
attachments: NoteAttachment[];
|
||||
pendingFiles: File[];
|
||||
onAttachmentsChange: (attachments: NoteAttachment[]) => void;
|
||||
onPendingFilesChange: (files: File[]) => void;
|
||||
onBusyChange?: (busy: boolean) => void;
|
||||
maxSizeMb?: number;
|
||||
disabled?: boolean;
|
||||
readonly?: boolean;
|
||||
}
|
||||
|
||||
export function NoteAttachmentsField({
|
||||
noteId,
|
||||
attachments,
|
||||
pendingFiles,
|
||||
onAttachmentsChange,
|
||||
onPendingFilesChange,
|
||||
onBusyChange,
|
||||
maxSizeMb = DEFAULT_MAX_FILE_SIZE_MB,
|
||||
disabled = false,
|
||||
readonly = false,
|
||||
}: NoteAttachmentsFieldProps) {
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [removing, setRemoving] = useState<NoteAttachment | null>(null);
|
||||
const [isRemoving, setIsRemoving] = useState(false);
|
||||
const [openingId, setOpeningId] = useState<string | null>(null);
|
||||
|
||||
async function addFiles(files: File[]) {
|
||||
const valid: File[] = [];
|
||||
for (const file of files) {
|
||||
const error = validateFile(file, maxSizeMb);
|
||||
if (error) toast.error(`${file.name}: ${error}`);
|
||||
else valid.push(file);
|
||||
}
|
||||
if (valid.length === 0) return;
|
||||
|
||||
if (!noteId) {
|
||||
onPendingFilesChange([...pendingFiles, ...valid]);
|
||||
return;
|
||||
}
|
||||
|
||||
setUploading(true);
|
||||
onBusyChange?.(true);
|
||||
const added: NoteAttachment[] = [];
|
||||
for (const file of valid) {
|
||||
const result = await uploadNoteAttachment(noteId, file);
|
||||
if (result.success) added.push(result.attachment);
|
||||
else toast.error(`${file.name}: ${result.error}`);
|
||||
}
|
||||
setUploading(false);
|
||||
onBusyChange?.(false);
|
||||
if (added.length > 0) {
|
||||
onAttachmentsChange([...attachments, ...added]);
|
||||
toast.success(
|
||||
added.length === 1
|
||||
? "Anexo enviado."
|
||||
: `${added.length} anexos enviados.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function downloadAttachment(attachment: NoteAttachment) {
|
||||
setOpeningId(attachment.attachmentId);
|
||||
try {
|
||||
const response = await fetch(
|
||||
`/api/attachments/${attachment.attachmentId}/presign`,
|
||||
);
|
||||
if (!response.ok) throw new Error();
|
||||
const { url } = (await response.json()) as { url: string };
|
||||
const anchor = document.createElement("a");
|
||||
anchor.href = url;
|
||||
anchor.download = attachment.fileName;
|
||||
anchor.target = "_blank";
|
||||
anchor.rel = "noreferrer";
|
||||
anchor.click();
|
||||
} catch {
|
||||
toast.error("Não foi possível baixar o anexo agora.");
|
||||
} finally {
|
||||
setOpeningId(null);
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmRemove() {
|
||||
if (!noteId || !removing) return;
|
||||
setIsRemoving(true);
|
||||
onBusyChange?.(true);
|
||||
const result = await removeNoteAttachmentAction({
|
||||
noteId,
|
||||
attachmentId: removing.attachmentId,
|
||||
});
|
||||
setIsRemoving(false);
|
||||
onBusyChange?.(false);
|
||||
if (result.success) {
|
||||
onAttachmentsChange(
|
||||
attachments.filter(
|
||||
(item) => item.attachmentId !== removing.attachmentId,
|
||||
),
|
||||
);
|
||||
setRemoving(null);
|
||||
toast.success(result.message);
|
||||
} else {
|
||||
toast.error(result.error);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-1.5">
|
||||
<p className="text-xs font-medium">Anexos</p>
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
multiple
|
||||
className="hidden"
|
||||
accept={ALLOWED_MIME_TYPES.join(",")}
|
||||
onChange={(event) => {
|
||||
void addFiles(Array.from(event.target.files ?? []));
|
||||
event.target.value = "";
|
||||
}}
|
||||
/>
|
||||
|
||||
{attachments.length > 0 && (
|
||||
<div className="space-y-1.5">
|
||||
{attachments.map((attachment) => (
|
||||
<div
|
||||
key={attachment.attachmentId}
|
||||
className="flex min-w-0 items-center gap-2 rounded-md border px-3 py-2 text-sm"
|
||||
>
|
||||
{attachment.mimeType === "application/pdf" ? (
|
||||
<RiFilePdf2Line className="size-4 shrink-0 text-red-500" />
|
||||
) : (
|
||||
<RiFileImageLine className="size-4 shrink-0 text-blue-500" />
|
||||
)}
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate font-medium" title={attachment.fileName}>
|
||||
{attachment.fileName}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{formatBytes(attachment.fileSize)}
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-7 shrink-0"
|
||||
disabled={openingId === attachment.attachmentId}
|
||||
onClick={() => void downloadAttachment(attachment)}
|
||||
aria-label={`Baixar ${attachment.fileName}`}
|
||||
>
|
||||
<RiDownloadLine className="size-4" />
|
||||
</Button>
|
||||
{!readonly && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-7 shrink-0 text-destructive hover:text-destructive"
|
||||
disabled={disabled}
|
||||
onClick={() => setRemoving(attachment)}
|
||||
aria-label={`Remover ${attachment.fileName}`}
|
||||
>
|
||||
<RiDeleteBinLine className="size-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{pendingFiles.map((file, index) => (
|
||||
<div
|
||||
key={`${file.name}-${file.size}-${file.lastModified}-${index}`}
|
||||
className="flex min-w-0 items-center gap-2 rounded-md border border-dashed px-3 py-2 text-sm"
|
||||
>
|
||||
<RiAttachment2 className="size-4 shrink-0 text-muted-foreground" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate font-medium">{file.name}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Será enviado ao salvar
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-7 shrink-0"
|
||||
onClick={() =>
|
||||
onPendingFilesChange(
|
||||
pendingFiles.filter((_, fileIndex) => fileIndex !== index),
|
||||
)
|
||||
}
|
||||
aria-label={`Cancelar ${file.name}`}
|
||||
>
|
||||
<RiCloseLine className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{!readonly && (
|
||||
<button
|
||||
type="button"
|
||||
className="flex min-h-16 w-full items-center justify-center gap-2 rounded-md border border-dashed px-3 text-sm text-muted-foreground transition-colors hover:border-foreground/40 hover:text-foreground disabled:pointer-events-none disabled:opacity-50"
|
||||
onClick={() => inputRef.current?.click()}
|
||||
disabled={disabled || uploading}
|
||||
>
|
||||
<RiAttachment2 className="size-4" />
|
||||
<span>{uploading ? "Enviando..." : "Adicionar anexos"}</span>
|
||||
<span className="hidden text-xs sm:inline">
|
||||
PDF ou imagem · máx. {maxSizeMb} MB
|
||||
</span>
|
||||
</button>
|
||||
)}
|
||||
|
||||
<Dialog
|
||||
open={Boolean(removing)}
|
||||
onOpenChange={(open) => !open && setRemoving(null)}
|
||||
>
|
||||
<DialogContent className="sm:max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Remover anexo?</DialogTitle>
|
||||
<DialogDescription>
|
||||
O arquivo {removing?.fileName} será removido desta nota.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<DialogClose asChild>
|
||||
<Button type="button" variant="outline" disabled={isRemoving}>
|
||||
Cancelar
|
||||
</Button>
|
||||
</DialogClose>
|
||||
<Button
|
||||
type="button"
|
||||
variant="destructive"
|
||||
disabled={isRemoving}
|
||||
onClick={() => void confirmRemove()}
|
||||
>
|
||||
{isRemoving ? "Removendo..." : "Remover"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import {
|
||||
RiArchiveLine,
|
||||
RiAttachment2,
|
||||
RiCheckLine,
|
||||
RiDeleteBin5Line,
|
||||
RiFileList2Line,
|
||||
@@ -87,11 +88,19 @@ export function NoteCard({
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{isTask && (
|
||||
<Badge variant="outline" className="shrink-0 text-xs">
|
||||
{completedCount}/{totalCount} concluídas
|
||||
</Badge>
|
||||
)}
|
||||
<div className="flex shrink-0 flex-col items-end gap-1.5">
|
||||
{isTask && (
|
||||
<Badge variant="outline" className="shrink-0 text-xs">
|
||||
{completedCount}/{totalCount} concluídas
|
||||
</Badge>
|
||||
)}
|
||||
{!isTask && note.attachments.length > 0 && (
|
||||
<Badge variant="outline" className="gap-1 text-xs">
|
||||
<RiAttachment2 className="size-3.5" />
|
||||
{note.attachments.length}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isTask ? (
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { RiCheckLine, RiSubtractLine } from "@remixicon/react";
|
||||
import { NoteAttachmentsField } from "@/features/notes/components/note-attachments-field";
|
||||
import {
|
||||
buildNoteDisplayTitle,
|
||||
formatNoteCreatedAtLong,
|
||||
@@ -85,8 +86,20 @@ export function NoteDetailsDialog({
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="max-h-[320px] overflow-auto whitespace-pre-line wrap-break-word text-sm text-foreground">
|
||||
{note.description}
|
||||
<div className="max-h-[55vh] space-y-4 overflow-auto">
|
||||
<div className="whitespace-pre-line wrap-break-word text-sm text-foreground">
|
||||
{note.description}
|
||||
</div>
|
||||
{note.attachments.length > 0 && (
|
||||
<NoteAttachmentsField
|
||||
noteId={note.id}
|
||||
attachments={note.attachments}
|
||||
pendingFiles={[]}
|
||||
onAttachmentsChange={() => undefined}
|
||||
onPendingFilesChange={() => undefined}
|
||||
readonly
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -15,6 +15,10 @@ import {
|
||||
} from "react";
|
||||
import { toast } from "sonner";
|
||||
import { createNoteAction, updateNoteAction } from "@/features/notes/actions";
|
||||
import {
|
||||
NoteAttachmentsField,
|
||||
uploadNoteAttachment,
|
||||
} from "@/features/notes/components/note-attachments-field";
|
||||
import { Button } from "@/shared/components/ui/button";
|
||||
import { Checkbox } from "@/shared/components/ui/checkbox";
|
||||
import {
|
||||
@@ -34,6 +38,7 @@ import { useFormState } from "@/shared/hooks/use-form-state";
|
||||
import { cn } from "@/shared/utils/ui";
|
||||
import {
|
||||
type Note,
|
||||
type NoteAttachment,
|
||||
type NoteFormValues,
|
||||
sortTasksByStatus,
|
||||
type Task,
|
||||
@@ -46,6 +51,7 @@ interface NoteDialogProps {
|
||||
note?: Note;
|
||||
open?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
attachmentMaxSizeMb?: number;
|
||||
}
|
||||
|
||||
const MAX_TITLE = 30;
|
||||
@@ -69,12 +75,16 @@ export function NoteDialog({
|
||||
note,
|
||||
open,
|
||||
onOpenChange,
|
||||
attachmentMaxSizeMb,
|
||||
}: NoteDialogProps) {
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
const [newTaskText, setNewTaskText] = useState("");
|
||||
const [editingTaskId, setEditingTaskId] = useState<string | null>(null);
|
||||
const [editingTaskText, setEditingTaskText] = useState("");
|
||||
const [noteAttachments, setNoteAttachments] = useState<NoteAttachment[]>([]);
|
||||
const [pendingFiles, setPendingFiles] = useState<File[]>([]);
|
||||
const [isAttachmentPending, setIsAttachmentPending] = useState(false);
|
||||
|
||||
const titleRef = useRef<HTMLInputElement>(null);
|
||||
const descRef = useRef<HTMLTextAreaElement>(null);
|
||||
@@ -99,6 +109,9 @@ export function NoteDialog({
|
||||
setNewTaskText("");
|
||||
setEditingTaskId(null);
|
||||
setEditingTaskText("");
|
||||
setNoteAttachments(note?.attachments ?? []);
|
||||
setPendingFiles([]);
|
||||
setIsAttachmentPending(false);
|
||||
requestAnimationFrame(() => titleRef.current?.focus());
|
||||
}
|
||||
}, [dialogOpen, note, resetForm]);
|
||||
@@ -137,12 +150,14 @@ export function NoteDialog({
|
||||
|
||||
const disableSubmit =
|
||||
isPending ||
|
||||
isAttachmentPending ||
|
||||
onlySpaces ||
|
||||
unchanged ||
|
||||
invalidLen ||
|
||||
Boolean(editingTaskId);
|
||||
|
||||
const handleOpenChange = (v: boolean) => {
|
||||
if (!v && (isPending || isAttachmentPending)) return;
|
||||
setDialogOpen(v);
|
||||
if (!v) setErrorMessage(null);
|
||||
};
|
||||
@@ -252,7 +267,9 @@ export function NoteDialog({
|
||||
}
|
||||
|
||||
startTransition(async () => {
|
||||
let result: { success: boolean; message?: string; error?: string };
|
||||
let result:
|
||||
| Awaited<ReturnType<typeof createNoteAction>>
|
||||
| Awaited<ReturnType<typeof updateNoteAction>>;
|
||||
if (mode === "create") {
|
||||
result = await createNoteAction(payload);
|
||||
} else {
|
||||
@@ -266,7 +283,31 @@ export function NoteDialog({
|
||||
}
|
||||
|
||||
if (result.success) {
|
||||
toast.success(result.message);
|
||||
if (mode === "create" && pendingFiles.length > 0) {
|
||||
const noteId = "data" in result ? result.data?.noteId : undefined;
|
||||
if (noteId) {
|
||||
let failedUploads = 0;
|
||||
for (const file of pendingFiles) {
|
||||
const upload = await uploadNoteAttachment(noteId, file);
|
||||
if (!upload.success) failedUploads += 1;
|
||||
}
|
||||
if (failedUploads > 0) {
|
||||
toast.warning(
|
||||
failedUploads === 1
|
||||
? "A nota foi salva, mas um anexo não pôde ser enviado."
|
||||
: `A nota foi salva, mas ${failedUploads} anexos não puderam ser enviados.`,
|
||||
);
|
||||
} else {
|
||||
toast.success(
|
||||
pendingFiles.length === 1
|
||||
? "Anotação e anexo salvos."
|
||||
: "Anotação e anexos salvos.",
|
||||
);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
toast.success(result.message);
|
||||
}
|
||||
setDialogOpen(false);
|
||||
return;
|
||||
}
|
||||
@@ -355,35 +396,48 @@ export function NoteDialog({
|
||||
</div>
|
||||
|
||||
{isNote && (
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label htmlFor="note-description">Conteúdo</Label>
|
||||
<span
|
||||
className={cn(
|
||||
"text-xs",
|
||||
descCount > MAX_DESC
|
||||
? "text-destructive"
|
||||
: "text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
{descCount}/{MAX_DESC}
|
||||
</span>
|
||||
<div className="space-y-3">
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label htmlFor="note-description">Conteúdo</Label>
|
||||
<span
|
||||
className={cn(
|
||||
"text-xs",
|
||||
descCount > MAX_DESC
|
||||
? "text-destructive"
|
||||
: "text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
{descCount}/{MAX_DESC}
|
||||
</span>
|
||||
</div>
|
||||
<Textarea
|
||||
id="note-description"
|
||||
className="field-sizing-fixed"
|
||||
ref={descRef}
|
||||
value={formState.description}
|
||||
onChange={(e) => updateField("description", e.target.value)}
|
||||
placeholder="Detalhe sua anotação..."
|
||||
rows={5}
|
||||
maxLength={MAX_DESC + 10}
|
||||
disabled={isPending}
|
||||
required
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Ctrl+Enter para salvar
|
||||
</p>
|
||||
</div>
|
||||
<Textarea
|
||||
id="note-description"
|
||||
className="field-sizing-fixed"
|
||||
ref={descRef}
|
||||
value={formState.description}
|
||||
onChange={(e) => updateField("description", e.target.value)}
|
||||
placeholder="Detalhe sua anotação..."
|
||||
rows={5}
|
||||
maxLength={MAX_DESC + 10}
|
||||
|
||||
<NoteAttachmentsField
|
||||
noteId={mode === "update" ? note?.id : undefined}
|
||||
attachments={noteAttachments}
|
||||
pendingFiles={pendingFiles}
|
||||
onAttachmentsChange={setNoteAttachments}
|
||||
onPendingFilesChange={setPendingFiles}
|
||||
onBusyChange={setIsAttachmentPending}
|
||||
maxSizeMb={attachmentMaxSizeMb}
|
||||
disabled={isPending}
|
||||
required
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Ctrl+Enter para salvar
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -517,7 +571,7 @@ export function NoteDialog({
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => handleOpenChange(false)}
|
||||
disabled={isPending}
|
||||
disabled={isPending || isAttachmentPending}
|
||||
>
|
||||
Cancelar
|
||||
</Button>
|
||||
|
||||
@@ -22,9 +22,14 @@ import type { Note } from "./types";
|
||||
interface NotesPageProps {
|
||||
notes: Note[];
|
||||
archivedNotes: Note[];
|
||||
attachmentMaxSizeMb?: number;
|
||||
}
|
||||
|
||||
export function NotesPage({ notes, archivedNotes }: NotesPageProps) {
|
||||
export function NotesPage({
|
||||
notes,
|
||||
archivedNotes,
|
||||
attachmentMaxSizeMb,
|
||||
}: NotesPageProps) {
|
||||
const [activeTab, setActiveTab] = useState("ativas");
|
||||
const [createOpen, setCreateOpen] = useState(false);
|
||||
const [editOpen, setEditOpen] = useState(false);
|
||||
@@ -192,6 +197,7 @@ export function NotesPage({ notes, archivedNotes }: NotesPageProps) {
|
||||
mode="create"
|
||||
open={createOpen}
|
||||
onOpenChange={handleCreateOpenChange}
|
||||
attachmentMaxSizeMb={attachmentMaxSizeMb}
|
||||
trigger={
|
||||
<Button className="w-full sm:w-auto">
|
||||
<RiAddFill className="size-4" />
|
||||
@@ -222,6 +228,7 @@ export function NotesPage({ notes, archivedNotes }: NotesPageProps) {
|
||||
note={noteToEdit ?? undefined}
|
||||
open={editOpen}
|
||||
onOpenChange={handleEditOpenChange}
|
||||
attachmentMaxSizeMb={attachmentMaxSizeMb}
|
||||
/>
|
||||
|
||||
<NoteDetailsDialog
|
||||
|
||||
@@ -14,6 +14,14 @@ export interface Note {
|
||||
tasks?: Task[];
|
||||
archived: boolean;
|
||||
createdAt: string;
|
||||
attachments: NoteAttachment[];
|
||||
}
|
||||
|
||||
export interface NoteAttachment {
|
||||
attachmentId: string;
|
||||
fileName: string;
|
||||
fileSize: number;
|
||||
mimeType: string;
|
||||
}
|
||||
|
||||
export interface NoteFormValues {
|
||||
|
||||
@@ -1,7 +1,14 @@
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { type Note, notes } from "@/db/schema";
|
||||
import { and, desc, eq } from "drizzle-orm";
|
||||
import { attachments, type Note, noteAttachments, notes } from "@/db/schema";
|
||||
import { db } from "@/shared/lib/db";
|
||||
|
||||
export type NoteAttachmentData = {
|
||||
attachmentId: string;
|
||||
fileName: string;
|
||||
fileSize: number;
|
||||
mimeType: string;
|
||||
};
|
||||
|
||||
type Task = {
|
||||
id: string;
|
||||
text: string;
|
||||
@@ -16,6 +23,7 @@ type NoteData = {
|
||||
tasks?: Task[];
|
||||
archived: boolean;
|
||||
createdAt: string;
|
||||
attachments: NoteAttachmentData[];
|
||||
};
|
||||
|
||||
function parseTasks(value: string | null): Task[] | undefined {
|
||||
@@ -31,7 +39,10 @@ function parseTasks(value: string | null): Task[] | undefined {
|
||||
}
|
||||
}
|
||||
|
||||
function toNoteData(note: Note): NoteData {
|
||||
function toNoteData(
|
||||
note: Note,
|
||||
linkedAttachments: NoteAttachmentData[],
|
||||
): NoteData {
|
||||
return {
|
||||
id: note.id,
|
||||
title: (note.title ?? "").trim(),
|
||||
@@ -40,34 +51,53 @@ function toNoteData(note: Note): NoteData {
|
||||
tasks: parseTasks(note.tasks),
|
||||
archived: note.archived,
|
||||
createdAt: note.createdAt.toISOString(),
|
||||
attachments: linkedAttachments,
|
||||
};
|
||||
}
|
||||
|
||||
async function fetchNotesForUser(userId: string): Promise<NoteData[]> {
|
||||
const noteRows = await db.query.notes.findMany({
|
||||
where: and(eq(notes.userId, userId), eq(notes.archived, false)),
|
||||
orderBy: (table, { desc }) => [desc(table.createdAt)],
|
||||
});
|
||||
|
||||
return noteRows.map(toNoteData);
|
||||
}
|
||||
|
||||
export async function fetchAllNotesForUser(
|
||||
userId: string,
|
||||
): Promise<{ activeNotes: NoteData[]; archivedNotes: NoteData[] }> {
|
||||
const [activeNotes, archivedNotes] = await Promise.all([
|
||||
fetchNotesForUser(userId),
|
||||
fetchArchivedForUser(userId),
|
||||
const [noteRows, attachmentRows] = await Promise.all([
|
||||
db.query.notes.findMany({
|
||||
where: eq(notes.userId, userId),
|
||||
orderBy: (table, { desc }) => [desc(table.createdAt)],
|
||||
}),
|
||||
db
|
||||
.select({
|
||||
noteId: noteAttachments.noteId,
|
||||
attachmentId: attachments.id,
|
||||
fileName: attachments.fileName,
|
||||
fileSize: attachments.fileSize,
|
||||
mimeType: attachments.mimeType,
|
||||
})
|
||||
.from(noteAttachments)
|
||||
.innerJoin(
|
||||
notes,
|
||||
and(eq(noteAttachments.noteId, notes.id), eq(notes.userId, userId)),
|
||||
)
|
||||
.innerJoin(
|
||||
attachments,
|
||||
and(
|
||||
eq(noteAttachments.attachmentId, attachments.id),
|
||||
eq(attachments.userId, userId),
|
||||
),
|
||||
)
|
||||
.orderBy(desc(attachments.createdAt)),
|
||||
]);
|
||||
|
||||
return { activeNotes, archivedNotes };
|
||||
}
|
||||
const attachmentsByNote = new Map<string, NoteAttachmentData[]>();
|
||||
for (const { noteId, ...attachment } of attachmentRows) {
|
||||
const current = attachmentsByNote.get(noteId) ?? [];
|
||||
current.push(attachment);
|
||||
attachmentsByNote.set(noteId, current);
|
||||
}
|
||||
const mapped = noteRows.map((note) =>
|
||||
toNoteData(note, attachmentsByNote.get(note.id) ?? []),
|
||||
);
|
||||
|
||||
async function fetchArchivedForUser(userId: string): Promise<NoteData[]> {
|
||||
const noteRows = await db.query.notes.findMany({
|
||||
where: and(eq(notes.userId, userId), eq(notes.archived, true)),
|
||||
orderBy: (table, { desc }) => [desc(table.createdAt)],
|
||||
});
|
||||
|
||||
return noteRows.map(toNoteData);
|
||||
return {
|
||||
activeNotes: mapped.filter((note) => !note.archived),
|
||||
archivedNotes: mapped.filter((note) => note.archived),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,13 +1,7 @@
|
||||
export const ALLOWED_MIME_TYPES = [
|
||||
"application/pdf",
|
||||
"image/jpeg",
|
||||
"image/png",
|
||||
"image/webp",
|
||||
] as const;
|
||||
|
||||
export const DEFAULT_MAX_FILE_SIZE_MB = 50;
|
||||
|
||||
export const MAX_FILE_SIZE = DEFAULT_MAX_FILE_SIZE_MB * 1024 * 1024; // 50MB (fallback)
|
||||
|
||||
export const ATTACHMENT_SIZE_OPTIONS = [5, 10, 25, 50, 100] as const;
|
||||
export type AttachmentSizeOption = (typeof ATTACHMENT_SIZE_OPTIONS)[number];
|
||||
export {
|
||||
ALLOWED_MIME_TYPES,
|
||||
ATTACHMENT_SIZE_OPTIONS,
|
||||
type AttachmentSizeOption,
|
||||
DEFAULT_MAX_FILE_SIZE_MB,
|
||||
MAX_FILE_SIZE,
|
||||
} from "@/shared/lib/attachments/config";
|
||||
|
||||
11
src/shared/lib/attachments/config.ts
Normal file
11
src/shared/lib/attachments/config.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
export const ALLOWED_MIME_TYPES = [
|
||||
"application/pdf",
|
||||
"image/jpeg",
|
||||
"image/png",
|
||||
"image/webp",
|
||||
] as const;
|
||||
|
||||
export const DEFAULT_MAX_FILE_SIZE_MB = 50;
|
||||
export const ATTACHMENT_SIZE_OPTIONS = [5, 10, 25, 50, 100] as const;
|
||||
export type AttachmentSizeOption = (typeof ATTACHMENT_SIZE_OPTIONS)[number];
|
||||
export const MAX_FILE_SIZE = DEFAULT_MAX_FILE_SIZE_MB * 1024 * 1024;
|
||||
Reference in New Issue
Block a user