feat(backend): migrate freelancer and portal runtimes
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import {
|
||||
ProjectDetailClient,
|
||||
type ProjectDetail,
|
||||
@@ -5,236 +6,91 @@ import {
|
||||
type ProjectFinanceItem,
|
||||
type ProjectPlanningSectionItem,
|
||||
} from "@/app/(dashboard)/projects/[id]/project-detail-client";
|
||||
import { createServiceRoleClient } from "@/lib/supabase/admin";
|
||||
import { createClient } from "@/lib/supabase/server";
|
||||
import { notFound } from "next/navigation";
|
||||
import { DomainError } from "@/server/domain/errors";
|
||||
import { requireFreelancerBackend } from "@/server/web/freelancer";
|
||||
|
||||
type ProjectRow = {
|
||||
id: string;
|
||||
client_id: string | null;
|
||||
name: string;
|
||||
type: "client_project" | "side_project";
|
||||
description: string | null;
|
||||
status: "planning" | "active" | "paused" | "completed" | "cancelled";
|
||||
start_date: string | null;
|
||||
due_date: string | null;
|
||||
budget_amount: number | string | null;
|
||||
currency: string;
|
||||
progress: number;
|
||||
progress_type: "manual" | "auto" | null;
|
||||
revision_quota: number | null;
|
||||
cover_image_path: string | null;
|
||||
cover_image_alt: string | null;
|
||||
clients: { name: string } | { name: string }[] | null;
|
||||
};
|
||||
|
||||
type SectionRow = ProjectPlanningSectionItem;
|
||||
|
||||
type TaskRow = {
|
||||
id: string;
|
||||
title: string;
|
||||
status: string | null;
|
||||
priority: string | null;
|
||||
due_at: string | null;
|
||||
is_public_to_client: boolean | null;
|
||||
};
|
||||
|
||||
type FinanceRow = {
|
||||
id: string;
|
||||
type: string;
|
||||
amount: number | string;
|
||||
currency: string;
|
||||
payment_status: string;
|
||||
transaction_date: string;
|
||||
category: string | null;
|
||||
};
|
||||
|
||||
export default async function ProjectDetailPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ id: string }>;
|
||||
}) {
|
||||
export default async function ProjectDetailPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await params;
|
||||
const supabase = await createClient();
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser();
|
||||
const { actor, service } = await requireFreelancerBackend();
|
||||
|
||||
if (!user) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const [{ data: projectRow }, { data: sectionRows }, { data: taskRows }, { data: financeRows }, { data: revisionRows }] =
|
||||
await Promise.all([
|
||||
supabase
|
||||
.from("projects")
|
||||
.select(
|
||||
"id, client_id, name, type, description, status, start_date, due_date, budget_amount, currency, progress, progress_type, revision_quota, cover_image_path, cover_image_alt, clients(name)",
|
||||
)
|
||||
.eq("id", id)
|
||||
.eq("user_id", user.id)
|
||||
.maybeSingle(),
|
||||
supabase
|
||||
.from("project_planning_sections")
|
||||
.select("id, project_id, category, title, content, sort_order")
|
||||
.eq("project_id", id)
|
||||
.eq("user_id", user.id)
|
||||
.order("sort_order", { ascending: true })
|
||||
.order("created_at", { ascending: true }),
|
||||
supabase
|
||||
.from("tasks")
|
||||
.select("id, title, status, priority, due_at, is_public_to_client")
|
||||
.eq("project_id", id)
|
||||
.eq("user_id", user.id)
|
||||
.order("created_at", { ascending: false }),
|
||||
supabase
|
||||
.from("finance_transactions")
|
||||
.select("id, type, amount, currency, payment_status, transaction_date, category")
|
||||
.eq("project_id", id)
|
||||
.eq("user_id", user.id)
|
||||
.order("transaction_date", { ascending: false }),
|
||||
supabase
|
||||
.from("project_revisions")
|
||||
.select("id, description, status, created_at, requested_by")
|
||||
.eq("project_id", id)
|
||||
.order("created_at", { ascending: false }),
|
||||
]);
|
||||
|
||||
if (!projectRow) {
|
||||
notFound();
|
||||
}
|
||||
|
||||
const projectData = projectRow as unknown as ProjectRow;
|
||||
const coverImageUrl = projectData.cover_image_path
|
||||
? await createProjectImageUrl(projectData.cover_image_path)
|
||||
: null;
|
||||
|
||||
const project: ProjectDetail = {
|
||||
id: projectData.id,
|
||||
client_id: projectData.client_id,
|
||||
clientName: getClientName(projectData.clients),
|
||||
name: projectData.name,
|
||||
type: normalizeProjectType(projectData.type),
|
||||
description: projectData.description,
|
||||
status: normalizeProjectStatus(projectData.status),
|
||||
start_date: projectData.start_date,
|
||||
due_date: projectData.due_date,
|
||||
budget_amount:
|
||||
projectData.budget_amount === null ? null : Number(projectData.budget_amount),
|
||||
currency: projectData.currency,
|
||||
progress: Number(projectData.progress || 0),
|
||||
progress_type: projectData.progress_type === "auto" ? "auto" : "manual",
|
||||
revision_quota: Number(projectData.revision_quota || 0),
|
||||
cover_image_alt: projectData.cover_image_alt,
|
||||
coverImageUrl,
|
||||
let data: {
|
||||
project: ProjectDetail;
|
||||
sections: ProjectPlanningSectionItem[];
|
||||
tasks: ProjectDetailTaskItem[];
|
||||
financeTransactions: ProjectFinanceItem[];
|
||||
revisions: Array<Record<string, unknown>>;
|
||||
};
|
||||
try {
|
||||
const row = service.getProject(actor, id);
|
||||
const client = row.clientId ? service.getClient(actor, row.clientId) : null;
|
||||
const project: ProjectDetail = {
|
||||
id: row.id,
|
||||
client_id: row.clientId,
|
||||
clientName: client?.name ?? null,
|
||||
name: row.name,
|
||||
type: row.type,
|
||||
description: row.description,
|
||||
status: row.status,
|
||||
start_date: row.startDate,
|
||||
due_date: row.dueDate,
|
||||
budget_amount: row.budgetAmountMinor == null ? null : row.budgetAmountMinor / 100,
|
||||
currency: row.currency,
|
||||
progress: row.progress,
|
||||
progress_type: row.progressType,
|
||||
revision_quota: row.revisionQuota,
|
||||
cover_image_alt: row.coverImageAlt,
|
||||
coverImageUrl: row.legacyCoverImagePath,
|
||||
};
|
||||
const sections: ProjectPlanningSectionItem[] = service.listPlanningSections(actor, id).map((section) => ({
|
||||
id: section.id,
|
||||
project_id: section.projectId,
|
||||
category: section.category,
|
||||
title: section.title,
|
||||
content: section.content,
|
||||
sort_order: section.sortOrder,
|
||||
}));
|
||||
const tasks: ProjectDetailTaskItem[] = service.listTasks(actor, id)
|
||||
.filter((task) => task.status !== "cancelled")
|
||||
.map((task) => ({
|
||||
id: task.id,
|
||||
title: task.title,
|
||||
status: task.status as ProjectDetailTaskItem["status"],
|
||||
priority: task.priority,
|
||||
due_at: task.dueAt?.toISOString() ?? null,
|
||||
is_public_to_client: task.isPublicToClient,
|
||||
}));
|
||||
const financeTransactions: ProjectFinanceItem[] = service.listFinanceTransactions(actor)
|
||||
.filter((transaction) => transaction.projectId === id)
|
||||
.map((transaction) => ({
|
||||
id: transaction.id,
|
||||
type: transaction.type,
|
||||
amount: transaction.amountMinor / 100,
|
||||
currency: transaction.currency,
|
||||
payment_status: transaction.paymentStatus,
|
||||
transaction_date: transaction.transactionDate,
|
||||
category: transaction.category,
|
||||
}));
|
||||
const revisions = service.listRevisions(actor, id).map((revision) => ({
|
||||
id: revision.id,
|
||||
description: revision.description,
|
||||
status: revision.status,
|
||||
created_at: revision.createdAt.toISOString(),
|
||||
requested_by: revision.requestedByUserId,
|
||||
}));
|
||||
|
||||
const sections = ((sectionRows || []) as unknown as SectionRow[]).map((section) => ({
|
||||
...section,
|
||||
category: normalizeSectionCategory(section.category),
|
||||
sort_order: Number(section.sort_order || 0),
|
||||
}));
|
||||
const tasks: ProjectDetailTaskItem[] = ((taskRows || []) as TaskRow[]).map((task) => ({
|
||||
id: task.id,
|
||||
title: task.title,
|
||||
status: normalizeTaskStatus(task.status),
|
||||
priority: normalizeTaskPriority(task.priority),
|
||||
due_at: task.due_at,
|
||||
is_public_to_client: task.is_public_to_client || false,
|
||||
}));
|
||||
const revisions = revisionRows || [];
|
||||
const financeTransactions: ProjectFinanceItem[] = ((financeRows || []) as FinanceRow[]).map(
|
||||
(transaction) => ({
|
||||
id: transaction.id,
|
||||
type: transaction.type === "income" ? "income" : "expense",
|
||||
amount: Number(transaction.amount || 0),
|
||||
currency: transaction.currency,
|
||||
payment_status: normalizePaymentStatus(transaction.payment_status),
|
||||
transaction_date: transaction.transaction_date,
|
||||
category: transaction.category,
|
||||
}),
|
||||
);
|
||||
data = { project, sections, tasks, financeTransactions, revisions };
|
||||
} catch (error) {
|
||||
if (error instanceof DomainError && error.code === "NOT_FOUND") notFound();
|
||||
throw error;
|
||||
}
|
||||
|
||||
return (
|
||||
<ProjectDetailClient
|
||||
project={project}
|
||||
sections={sections}
|
||||
tasks={tasks}
|
||||
financeTransactions={financeTransactions}
|
||||
revisions={revisions}
|
||||
project={data.project}
|
||||
sections={data.sections}
|
||||
tasks={data.tasks}
|
||||
financeTransactions={data.financeTransactions}
|
||||
revisions={data.revisions}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
async function createProjectImageUrl(path: string) {
|
||||
const admin = createServiceRoleClient();
|
||||
const { data } = await admin.storage
|
||||
.from("project-assets")
|
||||
.createSignedUrl(path, 60 * 15);
|
||||
|
||||
return data?.signedUrl || null;
|
||||
}
|
||||
|
||||
function getClientName(client: ProjectRow["clients"]) {
|
||||
if (!client) return null;
|
||||
return Array.isArray(client) ? client[0]?.name || null : client.name;
|
||||
}
|
||||
|
||||
function normalizeProjectType(type: string): ProjectDetail["type"] {
|
||||
return type === "side_project" ? "side_project" : "client_project";
|
||||
}
|
||||
|
||||
function normalizeProjectStatus(status: string): ProjectDetail["status"] {
|
||||
if (
|
||||
status === "active" ||
|
||||
status === "paused" ||
|
||||
status === "completed" ||
|
||||
status === "cancelled"
|
||||
) {
|
||||
return status;
|
||||
}
|
||||
|
||||
return "planning";
|
||||
}
|
||||
|
||||
function normalizeSectionCategory(category: string): ProjectPlanningSectionItem["category"] {
|
||||
if (
|
||||
category === "problem" ||
|
||||
category === "goal" ||
|
||||
category === "audience" ||
|
||||
category === "scope" ||
|
||||
category === "design_system" ||
|
||||
category === "color_palette" ||
|
||||
category === "typography" ||
|
||||
category === "assets" ||
|
||||
category === "notes"
|
||||
) {
|
||||
return category;
|
||||
}
|
||||
|
||||
return "overview";
|
||||
}
|
||||
|
||||
function normalizeTaskStatus(status: string | null): ProjectDetailTaskItem["status"] {
|
||||
if (status === "in_progress" || status === "done") {
|
||||
return status;
|
||||
}
|
||||
|
||||
return "todo";
|
||||
}
|
||||
|
||||
function normalizeTaskPriority(priority: string | null): ProjectDetailTaskItem["priority"] {
|
||||
if (priority === "low" || priority === "high" || priority === "urgent") {
|
||||
return priority;
|
||||
}
|
||||
|
||||
return "medium";
|
||||
}
|
||||
|
||||
function normalizePaymentStatus(status: string): ProjectFinanceItem["payment_status"] {
|
||||
if (status === "pending" || status === "paid" || status === "cancelled") {
|
||||
return status;
|
||||
}
|
||||
|
||||
return "planned";
|
||||
}
|
||||
|
||||
@@ -1,361 +1,152 @@
|
||||
"use server";
|
||||
|
||||
import { createClient } from "@/lib/supabase/server";
|
||||
import { createServiceRoleClient } from "@/lib/supabase/admin";
|
||||
import { randomUUID } from "crypto";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { getFileService } from "@/server/files/runtime";
|
||||
import { cleanText, decimalToMinor, requiredText } from "@/server/web/form-data";
|
||||
import { requireFreelancerBackend } from "@/server/web/freelancer";
|
||||
|
||||
const PROJECT_TYPES = ["client_project", "side_project"] as const;
|
||||
const PROJECT_STATUSES = ["planning", "active", "paused", "completed", "cancelled"] as const;
|
||||
const PLANNING_SECTION_CATEGORIES = [
|
||||
"overview",
|
||||
"problem",
|
||||
"goal",
|
||||
"audience",
|
||||
"scope",
|
||||
"design_system",
|
||||
"color_palette",
|
||||
"typography",
|
||||
"assets",
|
||||
"notes",
|
||||
] as const;
|
||||
const PROJECT_ASSETS_BUCKET = "project-assets";
|
||||
const SECTION_CATEGORIES = ["overview", "problem", "goal", "audience", "scope", "design_system", "color_palette", "typography", "assets", "notes"] as const;
|
||||
const REVISION_STATUSES = ["pending", "in_progress", "completed", "rejected"] as const;
|
||||
|
||||
function cleanText(value: FormDataEntryValue | null) {
|
||||
const text = typeof value === "string" ? value.trim() : "";
|
||||
return text.length > 0 ? text : null;
|
||||
function enumValue<T extends readonly string[]>(value: FormDataEntryValue | string | null, values: T, fallback: T[number]): T[number] {
|
||||
return typeof value === "string" && values.includes(value) ? value as T[number] : fallback;
|
||||
}
|
||||
|
||||
function readProjectType(value: FormDataEntryValue | null) {
|
||||
const type = typeof value === "string" ? value : "client_project";
|
||||
return PROJECT_TYPES.includes(type as (typeof PROJECT_TYPES)[number])
|
||||
? type
|
||||
: "client_project";
|
||||
function numberValue(value: FormDataEntryValue | null, fallback = 0) {
|
||||
const parsed = Number(typeof value === "string" ? value.replace(",", ".") : value);
|
||||
return Number.isFinite(parsed) ? parsed : fallback;
|
||||
}
|
||||
|
||||
function readProjectStatus(value: FormDataEntryValue | null) {
|
||||
const status = typeof value === "string" ? value : "planning";
|
||||
return PROJECT_STATUSES.includes(status as (typeof PROJECT_STATUSES)[number])
|
||||
? status
|
||||
: "planning";
|
||||
}
|
||||
|
||||
function readPlanningSectionCategory(value: FormDataEntryValue | null) {
|
||||
const category = typeof value === "string" ? value : "overview";
|
||||
return PLANNING_SECTION_CATEGORIES.includes(
|
||||
category as (typeof PLANNING_SECTION_CATEGORIES)[number],
|
||||
)
|
||||
? category
|
||||
: "overview";
|
||||
}
|
||||
|
||||
function readNumber(value: FormDataEntryValue | null) {
|
||||
const number = Number(typeof value === "string" ? value.replace(",", ".") : value);
|
||||
return Number.isFinite(number) ? number : null;
|
||||
}
|
||||
|
||||
function readProgress(value: FormDataEntryValue | null) {
|
||||
const progress = Math.round(readNumber(value) ?? 0);
|
||||
return Math.min(Math.max(progress, 0), 100);
|
||||
}
|
||||
|
||||
async function getCurrentUserId() {
|
||||
const supabase = await createClient();
|
||||
const {
|
||||
data: { user },
|
||||
error,
|
||||
} = await supabase.auth.getUser();
|
||||
|
||||
if (error || !user) {
|
||||
throw new Error("Proje işlemi için giriş yapmış kullanıcı bulunamadı.");
|
||||
}
|
||||
|
||||
return { supabase, userId: user.id };
|
||||
}
|
||||
|
||||
function readPayload(formData: FormData) {
|
||||
const type = readProjectType(formData.get("type"));
|
||||
const clientId = cleanText(formData.get("client_id"));
|
||||
|
||||
function projectPayload(formData: FormData) {
|
||||
const type = enumValue(formData.get("type"), PROJECT_TYPES, "client_project");
|
||||
return {
|
||||
name: cleanText(formData.get("name")),
|
||||
name: requiredText(formData.get("name"), "Proje adı zorunludur."),
|
||||
type,
|
||||
client_id: type === "client_project" ? clientId : null,
|
||||
clientId: type === "client_project" ? cleanText(formData.get("client_id")) : null,
|
||||
description: cleanText(formData.get("description")),
|
||||
status: readProjectStatus(formData.get("status")),
|
||||
start_date: cleanText(formData.get("start_date")),
|
||||
due_date: cleanText(formData.get("due_date")),
|
||||
budget_amount: readNumber(formData.get("budget_amount")),
|
||||
currency: cleanText(formData.get("currency")) || "USD",
|
||||
progress: readProgress(formData.get("progress")),
|
||||
cover_image_alt: cleanText(formData.get("cover_image_alt")),
|
||||
status: enumValue(formData.get("status"), PROJECT_STATUSES, "planning"),
|
||||
startDate: cleanText(formData.get("start_date")),
|
||||
dueDate: cleanText(formData.get("due_date")),
|
||||
budgetAmountMinor: decimalToMinor(formData.get("budget_amount")),
|
||||
currency: cleanText(formData.get("currency")) ?? "USD",
|
||||
progress: Math.min(100, Math.max(0, Math.round(numberValue(formData.get("progress"))))),
|
||||
coverImageAlt: cleanText(formData.get("cover_image_alt")),
|
||||
};
|
||||
}
|
||||
|
||||
function readImageFile(formData: FormData) {
|
||||
async function uploadCover(
|
||||
actor: Parameters<ReturnType<typeof getFileService>["upload"]>[0],
|
||||
projectId: string,
|
||||
formData: FormData,
|
||||
) {
|
||||
const file = formData.get("cover_image");
|
||||
|
||||
if (!(file instanceof File) || file.size === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!file.type.startsWith("image/")) {
|
||||
throw new Error("Kapak görseli bir görsel dosyası olmalıdır.");
|
||||
}
|
||||
|
||||
return file;
|
||||
}
|
||||
|
||||
function sanitizeFileName(name: string) {
|
||||
return name
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9._-]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "")
|
||||
.slice(0, 120);
|
||||
}
|
||||
|
||||
async function uploadCoverImage({
|
||||
userId,
|
||||
projectId,
|
||||
formData,
|
||||
}: {
|
||||
userId: string;
|
||||
projectId: string;
|
||||
formData: FormData;
|
||||
}) {
|
||||
const file = readImageFile(formData);
|
||||
|
||||
if (!file) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const fileName = `${Date.now()}-${sanitizeFileName(file.name) || "cover-image"}`;
|
||||
const path = `${userId}/projects/${projectId}/${fileName}`;
|
||||
const admin = createServiceRoleClient();
|
||||
const { error } = await admin.storage
|
||||
.from(PROJECT_ASSETS_BUCKET)
|
||||
.upload(path, file, {
|
||||
cacheControl: "3600",
|
||||
contentType: file.type,
|
||||
upsert: true,
|
||||
});
|
||||
|
||||
if (error) {
|
||||
throw new Error(`Kapak görseli yüklenemedi: ${error.message}`);
|
||||
}
|
||||
|
||||
return path;
|
||||
if (!(file instanceof File) || file.size === 0) return null;
|
||||
const stored = getFileService().upload(actor, {
|
||||
kind: "project_asset",
|
||||
originalName: file.name,
|
||||
claimedMimeType: file.type,
|
||||
bytes: new Uint8Array(await file.arrayBuffer()),
|
||||
projectId,
|
||||
portalVisible: true,
|
||||
});
|
||||
return `/api/files/${stored.id}`;
|
||||
}
|
||||
|
||||
export async function createProjectRecord(formData: FormData) {
|
||||
const { supabase, userId } = await getCurrentUserId();
|
||||
const projectId = randomUUID();
|
||||
const payload = readPayload(formData);
|
||||
|
||||
if (!payload.name) {
|
||||
throw new Error("Proje adı zorunludur.");
|
||||
const { actor, service } = await requireFreelancerBackend();
|
||||
const id = randomUUID();
|
||||
service.createProject(actor, { id, ...projectPayload(formData) });
|
||||
try {
|
||||
const cover = await uploadCover(actor, id, formData);
|
||||
if (cover) service.updateProject(actor, id, { legacyCoverImagePath: cover });
|
||||
} catch (error) {
|
||||
service.deleteProject(actor, id);
|
||||
throw error;
|
||||
}
|
||||
|
||||
const coverImagePath = await uploadCoverImage({
|
||||
userId,
|
||||
projectId,
|
||||
formData,
|
||||
});
|
||||
|
||||
const { error } = await supabase.from("projects").insert({
|
||||
id: projectId,
|
||||
user_id: userId,
|
||||
...payload,
|
||||
cover_image_path: coverImagePath,
|
||||
});
|
||||
|
||||
if (error) {
|
||||
throw new Error(`Proje eklenemedi: ${error.message}`);
|
||||
}
|
||||
|
||||
revalidatePath("/projects");
|
||||
}
|
||||
|
||||
export async function updateProjectRecord(formData: FormData) {
|
||||
const { supabase, userId } = await getCurrentUserId();
|
||||
const id = cleanText(formData.get("id"));
|
||||
const payload = readPayload(formData);
|
||||
|
||||
if (!id || !payload.name) {
|
||||
throw new Error("Proje güncellemek için proje adı ve kayıt kimliği zorunludur.");
|
||||
}
|
||||
|
||||
const coverImagePath = await uploadCoverImage({
|
||||
userId,
|
||||
projectId: id,
|
||||
formData,
|
||||
});
|
||||
|
||||
const updatePayload = {
|
||||
...payload,
|
||||
...(coverImagePath ? { cover_image_path: coverImagePath } : {}),
|
||||
};
|
||||
|
||||
const { error } = await supabase
|
||||
.from("projects")
|
||||
.update(updatePayload)
|
||||
.eq("id", id)
|
||||
.eq("user_id", userId);
|
||||
|
||||
if (error) {
|
||||
throw new Error(`Proje güncellenemedi: ${error.message}`);
|
||||
}
|
||||
|
||||
revalidatePath("/projects");
|
||||
}
|
||||
|
||||
export async function completeProjectRecord(formData: FormData) {
|
||||
const { supabase, userId } = await getCurrentUserId();
|
||||
const id = cleanText(formData.get("id"));
|
||||
|
||||
if (!id) {
|
||||
throw new Error("Tamamlanacak proje bulunamadı.");
|
||||
}
|
||||
|
||||
const { error } = await supabase
|
||||
.from("projects")
|
||||
.update({ status: "completed", progress: 100 })
|
||||
.eq("id", id)
|
||||
.eq("user_id", userId);
|
||||
|
||||
if (error) {
|
||||
throw new Error(`Proje tamamlanamadı: ${error.message}`);
|
||||
}
|
||||
|
||||
const { actor, service } = await requireFreelancerBackend();
|
||||
const id = requiredText(formData.get("id"), "Proje kaydı bulunamadı.");
|
||||
service.updateProject(actor, id, projectPayload(formData));
|
||||
const cover = await uploadCover(actor, id, formData);
|
||||
if (cover) service.updateProject(actor, id, { legacyCoverImagePath: cover });
|
||||
revalidatePath("/projects");
|
||||
revalidatePath(`/projects/${id}`);
|
||||
}
|
||||
|
||||
function readPlanningSectionPayload(formData: FormData) {
|
||||
export async function completeProjectRecord(formData: FormData) {
|
||||
const { actor, service } = await requireFreelancerBackend();
|
||||
const id = requiredText(formData.get("id"), "Tamamlanacak proje bulunamadı.");
|
||||
service.updateProject(actor, id, { status: "completed", progress: 100 });
|
||||
revalidatePath("/projects");
|
||||
revalidatePath(`/projects/${id}`);
|
||||
}
|
||||
|
||||
function sectionPayload(formData: FormData) {
|
||||
return {
|
||||
project_id: cleanText(formData.get("project_id")),
|
||||
category: readPlanningSectionCategory(formData.get("category")),
|
||||
title: cleanText(formData.get("title")),
|
||||
projectId: requiredText(formData.get("project_id"), "Proje zorunludur."),
|
||||
category: enumValue(formData.get("category"), SECTION_CATEGORIES, "overview"),
|
||||
title: requiredText(formData.get("title"), "Planlama başlığı zorunludur."),
|
||||
content: cleanText(formData.get("content")),
|
||||
sort_order: Math.round(readNumber(formData.get("sort_order")) ?? 0),
|
||||
sortOrder: Math.max(0, Math.round(numberValue(formData.get("sort_order")))),
|
||||
};
|
||||
}
|
||||
|
||||
export async function createProjectPlanningSectionRecord(formData: FormData) {
|
||||
const { supabase, userId } = await getCurrentUserId();
|
||||
const payload = readPlanningSectionPayload(formData);
|
||||
|
||||
if (!payload.project_id || !payload.title) {
|
||||
throw new Error("Planlama alanı eklemek için proje ve başlık zorunludur.");
|
||||
}
|
||||
|
||||
const { error } = await supabase.from("project_planning_sections").insert({
|
||||
user_id: userId,
|
||||
project_id: payload.project_id,
|
||||
category: payload.category,
|
||||
title: payload.title,
|
||||
content: payload.content,
|
||||
sort_order: payload.sort_order,
|
||||
});
|
||||
|
||||
if (error) {
|
||||
throw new Error(`Planlama alanı eklenemedi: ${error.message}`);
|
||||
}
|
||||
|
||||
const { actor, service } = await requireFreelancerBackend();
|
||||
const payload = sectionPayload(formData);
|
||||
service.addPlanningSection(actor, payload);
|
||||
revalidatePath("/projects");
|
||||
revalidatePath(`/projects/${payload.project_id}`);
|
||||
revalidatePath(`/projects/${payload.projectId}`);
|
||||
}
|
||||
|
||||
export async function updateProjectPlanningSectionRecord(formData: FormData) {
|
||||
const { supabase, userId } = await getCurrentUserId();
|
||||
const id = cleanText(formData.get("id"));
|
||||
const payload = readPlanningSectionPayload(formData);
|
||||
|
||||
if (!id || !payload.project_id || !payload.title) {
|
||||
throw new Error("Planlama alanını güncellemek için kayıt kimliği, proje ve başlık zorunludur.");
|
||||
const { actor, service } = await requireFreelancerBackend();
|
||||
const id = requiredText(formData.get("id"), "Planlama alanı bulunamadı.");
|
||||
const payload = sectionPayload(formData);
|
||||
if (!service.listPlanningSections(actor, payload.projectId).some((section) => section.id === id)) {
|
||||
throw new Error("Planlama alanı bu projeye ait değil.");
|
||||
}
|
||||
|
||||
const { error } = await supabase
|
||||
.from("project_planning_sections")
|
||||
.update({
|
||||
category: payload.category,
|
||||
title: payload.title,
|
||||
content: payload.content,
|
||||
sort_order: payload.sort_order,
|
||||
})
|
||||
.eq("id", id)
|
||||
.eq("project_id", payload.project_id)
|
||||
.eq("user_id", userId);
|
||||
|
||||
if (error) {
|
||||
throw new Error(`Planlama alanı güncellenemedi: ${error.message}`);
|
||||
}
|
||||
|
||||
service.updatePlanningSection(actor, id, {
|
||||
category: payload.category,
|
||||
title: payload.title,
|
||||
content: payload.content,
|
||||
sortOrder: payload.sortOrder,
|
||||
});
|
||||
revalidatePath("/projects");
|
||||
revalidatePath(`/projects/${payload.project_id}`);
|
||||
revalidatePath(`/projects/${payload.projectId}`);
|
||||
}
|
||||
|
||||
export async function deleteProjectPlanningSectionRecord(formData: FormData) {
|
||||
const { supabase, userId } = await getCurrentUserId();
|
||||
const id = cleanText(formData.get("id"));
|
||||
const projectId = cleanText(formData.get("project_id"));
|
||||
|
||||
if (!id || !projectId) {
|
||||
throw new Error("Silinecek planlama alanı bulunamadı.");
|
||||
const { actor, service } = await requireFreelancerBackend();
|
||||
const id = requiredText(formData.get("id"), "Silinecek planlama alanı bulunamadı.");
|
||||
const projectId = requiredText(formData.get("project_id"), "Proje zorunludur.");
|
||||
if (!service.listPlanningSections(actor, projectId).some((section) => section.id === id)) {
|
||||
throw new Error("Planlama alanı bu projeye ait değil.");
|
||||
}
|
||||
|
||||
const { error } = await supabase
|
||||
.from("project_planning_sections")
|
||||
.delete()
|
||||
.eq("id", id)
|
||||
.eq("project_id", projectId)
|
||||
.eq("user_id", userId);
|
||||
|
||||
if (error) {
|
||||
throw new Error(`Planlama alanı silinemedi: ${error.message}`);
|
||||
}
|
||||
|
||||
service.deletePlanningSection(actor, id);
|
||||
revalidatePath("/projects");
|
||||
revalidatePath(`/projects/${projectId}`);
|
||||
}
|
||||
|
||||
export async function updateRevisionStatus(id: string, projectId: string, status: string) {
|
||||
const { supabase } = await getCurrentUserId();
|
||||
|
||||
const { error } = await supabase
|
||||
.from("project_revisions")
|
||||
.update({ status })
|
||||
.eq("id", id)
|
||||
.eq("project_id", projectId);
|
||||
|
||||
if (error) {
|
||||
throw new Error(`Revizyon durumu güncellenemedi: ${error.message}`);
|
||||
}
|
||||
|
||||
const { actor, service } = await requireFreelancerBackend();
|
||||
service.updateRevisionStatus(actor, id, enumValue(status, REVISION_STATUSES, "pending"), projectId);
|
||||
revalidatePath(`/projects/${projectId}`);
|
||||
}
|
||||
|
||||
export async function updateProjectSettings(projectId: string, progressType: "manual" | "auto", progress: number, revisionQuota: number) {
|
||||
const { supabase, userId } = await getCurrentUserId();
|
||||
|
||||
if (!projectId) {
|
||||
throw new Error("Proje ID zorunludur.");
|
||||
}
|
||||
|
||||
const { error } = await supabase
|
||||
.from("projects")
|
||||
.update({
|
||||
progress_type: progressType,
|
||||
progress: progress,
|
||||
revision_quota: revisionQuota
|
||||
})
|
||||
.eq("id", projectId)
|
||||
.eq("user_id", userId);
|
||||
|
||||
if (error) {
|
||||
throw new Error(`Ayarlar güncellenemedi: ${error.message}`);
|
||||
}
|
||||
|
||||
const { actor, service } = await requireFreelancerBackend();
|
||||
service.updateProject(actor, projectId, {
|
||||
progressType,
|
||||
progress: Math.min(100, Math.max(0, Math.round(progress))),
|
||||
revisionQuota: Math.max(0, Math.round(revisionQuota)),
|
||||
});
|
||||
revalidatePath("/projects");
|
||||
revalidatePath(`/projects/${projectId}`);
|
||||
}
|
||||
|
||||
@@ -1,139 +1,48 @@
|
||||
import {
|
||||
ProjectsClient,
|
||||
type ProjectClientOption,
|
||||
type ProjectListItem,
|
||||
} from "@/app/(dashboard)/projects/projects-client";
|
||||
import { createClient } from "@/lib/supabase/server";
|
||||
import { createServiceRoleClient } from "@/lib/supabase/admin";
|
||||
|
||||
type ProjectRow = {
|
||||
id: string;
|
||||
user_id: string;
|
||||
client_id: string | null;
|
||||
name: string;
|
||||
type: "client_project" | "side_project";
|
||||
description: string | null;
|
||||
status: "planning" | "active" | "paused" | "completed" | "cancelled";
|
||||
start_date: string | null;
|
||||
due_date: string | null;
|
||||
budget_amount: number | string | null;
|
||||
currency: string;
|
||||
progress: number;
|
||||
cover_image_path: string | null;
|
||||
cover_image_alt: string | null;
|
||||
clients: { name: string } | { name: string }[] | null;
|
||||
};
|
||||
|
||||
type TaskRow = {
|
||||
project_id: string | null;
|
||||
status: string | null;
|
||||
};
|
||||
import { ProjectsClient, type ProjectClientOption, type ProjectListItem } from "@/app/(dashboard)/projects/projects-client";
|
||||
import { requireFreelancerBackend } from "@/server/web/freelancer";
|
||||
|
||||
export default async function ProjectsPage() {
|
||||
const supabase = await createClient();
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser();
|
||||
const { actor, service } = await requireFreelancerBackend();
|
||||
const projectRows = service.listProjects(actor);
|
||||
const clientRows = service.listClients(actor);
|
||||
const taskRows = service.listTasks(actor);
|
||||
const clientNames = new Map(clientRows.map((client) => [client.id, client.name]));
|
||||
const taskStats = new Map<string, { total: number; done: number }>();
|
||||
|
||||
if (!user) {
|
||||
return null;
|
||||
for (const task of taskRows) {
|
||||
if (!task.projectId || task.status === "cancelled") continue;
|
||||
const stats = taskStats.get(task.projectId) ?? { total: 0, done: 0 };
|
||||
stats.total += 1;
|
||||
if (task.status === "done") stats.done += 1;
|
||||
taskStats.set(task.projectId, stats);
|
||||
}
|
||||
|
||||
const [{ data: projectRows }, { data: clientRows }, { data: taskRows }] =
|
||||
await Promise.all([
|
||||
supabase
|
||||
.from("projects")
|
||||
.select(
|
||||
"id, user_id, client_id, name, type, description, status, start_date, due_date, budget_amount, currency, progress, cover_image_path, cover_image_alt, clients(name)",
|
||||
)
|
||||
.eq("user_id", user.id)
|
||||
.order("created_at", { ascending: false }),
|
||||
supabase
|
||||
.from("clients")
|
||||
.select("id, name")
|
||||
.eq("user_id", user.id)
|
||||
.neq("status", "archived")
|
||||
.order("name", { ascending: true }),
|
||||
supabase.from("tasks").select("project_id, status").eq("user_id", user.id),
|
||||
]);
|
||||
|
||||
const taskStats = countTasksByProject((taskRows || []) as TaskRow[]);
|
||||
const clients = (clientRows || []) as ProjectClientOption[];
|
||||
const signedUrls = await createProjectImageUrls(
|
||||
((projectRows || []) as unknown as ProjectRow[])
|
||||
.map((project) => project.cover_image_path)
|
||||
.filter(Boolean) as string[],
|
||||
);
|
||||
|
||||
const projects: ProjectListItem[] = ((projectRows || []) as unknown as ProjectRow[]).map((project) => {
|
||||
const stats = taskStats.get(project.id) || { total: 0, done: 0 };
|
||||
|
||||
const projects: ProjectListItem[] = projectRows.map((project) => {
|
||||
const stats = taskStats.get(project.id) ?? { total: 0, done: 0 };
|
||||
return {
|
||||
id: project.id,
|
||||
client_id: project.client_id,
|
||||
clientName: getClientName(project.clients),
|
||||
client_id: project.clientId,
|
||||
clientName: project.clientId ? clientNames.get(project.clientId) ?? null : null,
|
||||
name: project.name,
|
||||
type: project.type,
|
||||
description: project.description,
|
||||
status: project.status,
|
||||
start_date: project.start_date,
|
||||
due_date: project.due_date,
|
||||
budget_amount: project.budget_amount === null ? null : Number(project.budget_amount),
|
||||
start_date: project.startDate,
|
||||
due_date: project.dueDate,
|
||||
budget_amount: project.budgetAmountMinor == null ? null : project.budgetAmountMinor / 100,
|
||||
currency: project.currency,
|
||||
progress: project.progress,
|
||||
cover_image_path: project.cover_image_path,
|
||||
cover_image_alt: project.cover_image_alt,
|
||||
coverImageUrl: project.cover_image_path ? signedUrls.get(project.cover_image_path) || null : null,
|
||||
cover_image_path: project.legacyCoverImagePath,
|
||||
cover_image_alt: project.coverImageAlt,
|
||||
coverImageUrl: project.legacyCoverImagePath,
|
||||
taskCount: stats.total,
|
||||
doneTaskCount: stats.done,
|
||||
};
|
||||
});
|
||||
const clients: ProjectClientOption[] = clientRows
|
||||
.filter((client) => client.status !== "archived")
|
||||
.sort((a, b) => a.name.localeCompare(b.name, "tr"))
|
||||
.map(({ id, name }) => ({ id, name }));
|
||||
|
||||
return <ProjectsClient projects={projects} clients={clients} />;
|
||||
}
|
||||
|
||||
async function createProjectImageUrls(
|
||||
paths: string[],
|
||||
) {
|
||||
const admin = createServiceRoleClient();
|
||||
const urls = new Map<string, string>();
|
||||
const uniquePaths = Array.from(new Set(paths));
|
||||
|
||||
await Promise.all(
|
||||
uniquePaths.map(async (path) => {
|
||||
const { data } = await admin.storage
|
||||
.from("project-assets")
|
||||
.createSignedUrl(path, 60 * 15);
|
||||
|
||||
if (data?.signedUrl) {
|
||||
urls.set(path, data.signedUrl);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
return urls;
|
||||
}
|
||||
|
||||
function getClientName(client: ProjectRow["clients"]) {
|
||||
if (!client) return null;
|
||||
return Array.isArray(client) ? client[0]?.name || null : client.name;
|
||||
}
|
||||
|
||||
function countTasksByProject(tasks: TaskRow[]) {
|
||||
const statsByProject = new Map<string, { total: number; done: number }>();
|
||||
|
||||
for (const task of tasks) {
|
||||
if (!task.project_id) continue;
|
||||
|
||||
const current = statsByProject.get(task.project_id) || { total: 0, done: 0 };
|
||||
current.total += 1;
|
||||
|
||||
if (task.status === "done") {
|
||||
current.done += 1;
|
||||
}
|
||||
|
||||
statsByProject.set(task.project_id, current);
|
||||
}
|
||||
|
||||
return statsByProject;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user