feat(i18n): localize finance journal and business modules
This commit is contained in:
@@ -1,11 +1,9 @@
|
||||
"use client";
|
||||
|
||||
import { getDocumentIntlLocale } from "@/lib/i18n/browser";
|
||||
import { useState } from "react";
|
||||
import { format } from "date-fns";
|
||||
import { getDocumentDateFnsLocale } from "@/lib/i18n/date-fns";
|
||||
import { Plus, MoreHorizontal, FileEdit, Trash2, Send, Download, CheckCircle2 } from "lucide-react";
|
||||
import { Button, Card, CardContent, Badge } from "poyraz-ui/atoms";
|
||||
import { useTranslations } from "@/components/i18n/i18n-provider";
|
||||
import { CheckCircle2, Download, FileEdit, MoreHorizontal, Plus, Send, Trash2 } from "lucide-react";
|
||||
import { Badge, Button, Card, CardContent } from "poyraz-ui/atoms";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
@@ -27,60 +25,38 @@ export type InvoiceRow = {
|
||||
};
|
||||
|
||||
export function InvoicesClient({ invoices }: { invoices: InvoiceRow[] }) {
|
||||
const [isAddModalOpen, setIsAddModalOpen] = useState(false);
|
||||
|
||||
const formatCurrency = (amount: number, currency: string) => {
|
||||
return new Intl.NumberFormat(getDocumentIntlLocale(), { style: "currency", currency }).format(amount);
|
||||
};
|
||||
|
||||
const getStatusBadge = (status: string) => {
|
||||
switch (status) {
|
||||
case "draft":
|
||||
return <Badge variant="secondary">Taslak</Badge>;
|
||||
case "sent":
|
||||
return <Badge className="bg-blue-500/10 text-blue-500 border-blue-500/20 hover:bg-blue-500/20">Gönderildi</Badge>;
|
||||
case "paid":
|
||||
return <Badge className="bg-emerald-500/10 text-emerald-500 border-emerald-500/20 hover:bg-emerald-500/20">Ödendi</Badge>;
|
||||
case "overdue":
|
||||
return <Badge variant="destructive">Gecikmiş</Badge>;
|
||||
case "cancelled":
|
||||
return <Badge variant="outline" className="opacity-50">İptal</Badge>;
|
||||
default:
|
||||
return <Badge variant="outline">{status}</Badge>;
|
||||
}
|
||||
};
|
||||
const t = useTranslations();
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6 w-full animate-in fade-in slide-in-from-bottom-4 duration-500">
|
||||
<div className="flex w-full flex-col gap-6 animate-in fade-in slide-in-from-bottom-4 duration-500">
|
||||
<div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold tracking-tight text-foreground">Faturalar</h1>
|
||||
</div>
|
||||
<Button variant="default" effect="shine" onClick={() => setIsAddModalOpen(true)} className="gap-2">
|
||||
<Plus className="h-4 w-4" /> Yeni Fatura
|
||||
<h1 className="text-3xl font-bold tracking-tight text-foreground">{t("business.invoices.title")}</h1>
|
||||
<Button variant="default" effect="shine" className="gap-2">
|
||||
<Plus className="h-4 w-4" /> {t("business.invoices.actions.add")}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardContent className="p-0">
|
||||
<div className="rounded-md border border-border">
|
||||
<div className="rounded-sm border border-border">
|
||||
<div className="relative w-full overflow-auto">
|
||||
<table className="w-full caption-bottom text-sm">
|
||||
<thead className="[&_tr]:border-b">
|
||||
<tr className="border-b border-border transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted">
|
||||
<th className="h-12 px-4 text-left align-middle font-medium text-muted-foreground">Fatura No</th>
|
||||
<th className="h-12 px-4 text-left align-middle font-medium text-muted-foreground">Müşteri</th>
|
||||
<th className="h-12 px-4 text-left align-middle font-medium text-muted-foreground">Tutar</th>
|
||||
<th className="h-12 px-4 text-left align-middle font-medium text-muted-foreground">Durum</th>
|
||||
<th className="h-12 px-4 text-left align-middle font-medium text-muted-foreground">Düzenlenme Tarihi</th>
|
||||
<th className="h-12 px-4 text-right align-middle font-medium text-muted-foreground">İşlemler</th>
|
||||
<tr className="border-b border-border transition-colors hover:bg-muted/50">
|
||||
<TableHead>{t("business.invoices.table.number")}</TableHead>
|
||||
<TableHead>{t("business.common.client")}</TableHead>
|
||||
<TableHead>{t("business.common.amount")}</TableHead>
|
||||
<TableHead>{t("business.common.status")}</TableHead>
|
||||
<TableHead>{t("business.invoices.table.issueDate")}</TableHead>
|
||||
<TableHead>{t("business.invoices.table.dueDate")}</TableHead>
|
||||
<TableHead className="text-right">{t("business.common.actions")}</TableHead>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="[&_tr:last-child]:border-0">
|
||||
{invoices.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={6} className="h-24 text-center text-muted-foreground">
|
||||
Henüz hiç fatura bulunmuyor.
|
||||
<td colSpan={7} className="h-32 text-center text-muted-foreground">
|
||||
{t("business.invoices.empty")}
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
@@ -88,48 +64,17 @@ export function InvoicesClient({ invoices }: { invoices: InvoiceRow[] }) {
|
||||
<tr key={invoice.id} className="border-b border-border transition-colors hover:bg-muted/50">
|
||||
<td className="p-4 align-middle font-medium text-foreground">
|
||||
{invoice.invoice_number}
|
||||
{invoice.projectName && (
|
||||
<div className="text-xs text-muted-foreground font-normal mt-0.5">{invoice.projectName}</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="p-4 align-middle text-muted-foreground">
|
||||
{invoice.clientName || "-"}
|
||||
</td>
|
||||
<td className="p-4 align-middle font-medium">
|
||||
{formatCurrency(invoice.amount, invoice.currency)}
|
||||
</td>
|
||||
<td className="p-4 align-middle">
|
||||
{getStatusBadge(invoice.status)}
|
||||
</td>
|
||||
<td className="p-4 align-middle text-muted-foreground">
|
||||
{invoice.issue_date ? format(new Date(invoice.issue_date), "dd MMM yyyy", { locale: getDocumentDateFnsLocale() }) : "-"}
|
||||
{invoice.projectName ? (
|
||||
<div className="mt-0.5 text-xs font-normal text-muted-foreground">{invoice.projectName}</div>
|
||||
) : null}
|
||||
</td>
|
||||
<td className="p-4 align-middle text-muted-foreground">{invoice.clientName || "-"}</td>
|
||||
<td className="p-4 align-middle font-medium">{formatCurrency(invoice.amount, invoice.currency)}</td>
|
||||
<td className="p-4 align-middle"><InvoiceStatusBadge status={invoice.status} /></td>
|
||||
<td className="p-4 align-middle text-muted-foreground">{invoice.issue_date ? formatDate(invoice.issue_date) : "-"}</td>
|
||||
<td className="p-4 align-middle text-muted-foreground">{invoice.due_date ? formatDate(invoice.due_date) : "-"}</td>
|
||||
<td className="p-4 align-middle text-right">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button size="icon-sm" effect="shine" variant="secondary" >
|
||||
<span className="sr-only">Menüyü aç</span>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem className="cursor-pointer">
|
||||
<FileEdit className="mr-2 h-4 w-4" /> Düzenle
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem className="cursor-pointer">
|
||||
<Download className="mr-2 h-4 w-4" /> PDF İndir
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem className="cursor-pointer">
|
||||
<Send className="mr-2 h-4 w-4" /> Gönder
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem className="cursor-pointer text-emerald-500 focus:text-emerald-500">
|
||||
<CheckCircle2 className="mr-2 h-4 w-4" /> Ödendi İşaretle
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem className="cursor-pointer text-destructive focus:text-destructive">
|
||||
<Trash2 className="mr-2 h-4 w-4" /> Sil
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<InvoiceMenu />
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
@@ -140,20 +85,59 @@ export function InvoicesClient({ invoices }: { invoices: InvoiceRow[] }) {
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{isAddModalOpen && (
|
||||
<div className="fixed inset-0 z-50 bg-background/80 backdrop-blur-sm flex items-center justify-center">
|
||||
<Card className="w-full max-w-md">
|
||||
<CardContent className="p-6">
|
||||
<h3 className="text-lg font-bold mb-4 text-foreground">Yeni Fatura Ekle</h3>
|
||||
<p className="text-sm text-muted-foreground mb-6">Bu özellik şu an geliştirme aşamasındadır.</p>
|
||||
<div className="flex justify-end">
|
||||
<Button effect="shine" variant="secondary" onClick={() => setIsAddModalOpen(false)}>Kapat</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function InvoiceMenu() {
|
||||
const t = useTranslations();
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button size="icon-sm" effect="shine" variant="secondary">
|
||||
<span className="sr-only">{t("business.common.openMenu")}</span>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem className="cursor-pointer">
|
||||
<FileEdit className="mr-2 h-4 w-4" /> {t("business.common.edit")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem className="cursor-pointer">
|
||||
<Download className="mr-2 h-4 w-4" /> {t("business.invoices.actions.download")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem className="cursor-pointer">
|
||||
<Send className="mr-2 h-4 w-4" /> {t("business.invoices.actions.send")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem className="cursor-pointer text-emerald-500 focus:text-emerald-500">
|
||||
<CheckCircle2 className="mr-2 h-4 w-4" /> {t("business.invoices.actions.markPaid")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem className="cursor-pointer text-destructive focus:text-destructive">
|
||||
<Trash2 className="mr-2 h-4 w-4" /> {t("business.common.delete")}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
}
|
||||
|
||||
function InvoiceStatusBadge({ status }: { status: InvoiceRow["status"] }) {
|
||||
const t = useTranslations();
|
||||
if (status === "draft") return <Badge variant="secondary">{t("business.invoices.status.draft")}</Badge>;
|
||||
if (status === "sent") return <Badge className="border-blue-500/20 bg-blue-500/10 text-blue-500">{t("business.invoices.status.sent")}</Badge>;
|
||||
if (status === "paid") return <Badge className="border-emerald-500/20 bg-emerald-500/10 text-emerald-500">{t("business.invoices.status.paid")}</Badge>;
|
||||
if (status === "overdue") return <Badge variant="destructive">{t("business.invoices.status.overdue")}</Badge>;
|
||||
return <Badge variant="outline" className="opacity-70">{t("business.invoices.status.cancelled")}</Badge>;
|
||||
}
|
||||
|
||||
function TableHead({ className = "", children }: { className?: string; children: React.ReactNode }) {
|
||||
return <th className={`h-12 px-4 text-left align-middle font-medium text-muted-foreground ${className}`}>{children}</th>;
|
||||
}
|
||||
|
||||
function formatCurrency(amount: number, currency: string) {
|
||||
return new Intl.NumberFormat(getDocumentIntlLocale(), { style: "currency", currency }).format(amount);
|
||||
}
|
||||
|
||||
function formatDate(value: string) {
|
||||
return new Intl.DateTimeFormat(getDocumentIntlLocale(), { day: "2-digit", month: "short", year: "numeric" }).format(new Date(`${value}T00:00:00`));
|
||||
}
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
import { requireFreelancerBackend } from "@/server/web/freelancer";
|
||||
import { resolveFreelancerLocale } from "@/server/i18n/resolver";
|
||||
import { getClientI18nPayload } from "@/server/i18n/translator";
|
||||
import { I18nProvider } from "@/components/i18n/i18n-provider";
|
||||
import { InvoicesClient, type InvoiceRow } from "./invoices-client";
|
||||
|
||||
export default async function InvoicesPage() {
|
||||
const { actor, service } = await requireFreelancerBackend();
|
||||
const { context, actor, service } = await requireFreelancerBackend();
|
||||
const locale = await resolveFreelancerLocale(context);
|
||||
const clientNames = new Map(service.listClients(actor).map((client) => [client.id, client.name]));
|
||||
const projectNames = new Map(service.listProjects(actor).map((project) => [project.id, project.name]));
|
||||
const invoices: InvoiceRow[] = service.listInvoices(actor).map((invoice) => ({
|
||||
@@ -18,5 +22,11 @@ export default async function InvoicesPage() {
|
||||
projectName: invoice.projectId ? projectNames.get(invoice.projectId) ?? null : null,
|
||||
}));
|
||||
|
||||
return <InvoicesClient invoices={invoices} />;
|
||||
const i18nPayload = getClientI18nPayload(locale.locale, ["business", "common"]);
|
||||
|
||||
return (
|
||||
<I18nProvider {...i18nPayload}>
|
||||
<InvoicesClient invoices={invoices} />
|
||||
</I18nProvider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { getSqliteConnection } from "@/server/db/client";
|
||||
import { ContentTranslationService, parseContentTranslationsFromFormData } from "@/server/i18n/content";
|
||||
import { cleanText, requiredText } from "@/server/web/form-data";
|
||||
import { requireFreelancerBackend } from "@/server/web/freelancer";
|
||||
|
||||
const STATUSES = ["draft", "sent", "accepted", "rejected"] as const;
|
||||
|
||||
function enumValue<T extends readonly string[]>(value: FormDataEntryValue | null, values: T, fallback: T[number]): T[number] {
|
||||
return typeof value === "string" && values.includes(value) ? value as T[number] : fallback;
|
||||
}
|
||||
|
||||
function payload(formData: FormData, translations: Record<string, Record<string, string | null>>, defaultLocale: string) {
|
||||
const amountMinor = amountToMinor(formData.get("amount"));
|
||||
if (amountMinor == null) throw new Error("business.proposals.errors.amountRequired");
|
||||
const localized = translations[defaultLocale] ?? {};
|
||||
|
||||
return {
|
||||
clientId: cleanText(formData.get("client_id")),
|
||||
projectId: cleanText(formData.get("project_id")),
|
||||
title: localized.title ?? "",
|
||||
description: localized.description ?? null,
|
||||
amountMinor,
|
||||
currency: cleanText(formData.get("currency")) ?? "TRY",
|
||||
status: enumValue(formData.get("status"), STATUSES, "draft"),
|
||||
validUntil: optionalBusinessDate(formData.get("valid_until")),
|
||||
};
|
||||
}
|
||||
|
||||
function amountToMinor(value: FormDataEntryValue | null) {
|
||||
const normalized = typeof value === "string" ? value.trim().replace(",", ".") : "";
|
||||
if (!normalized) return null;
|
||||
const amount = Number(normalized);
|
||||
if (!Number.isFinite(amount) || amount < 0) throw new Error("business.proposals.errors.amountRequired");
|
||||
return Math.round((amount + Number.EPSILON) * 100);
|
||||
}
|
||||
|
||||
function optionalBusinessDate(value: FormDataEntryValue | null) {
|
||||
const text = cleanText(value);
|
||||
if (!text) return null;
|
||||
const date = new Date(`${text}T00:00:00`);
|
||||
if (Number.isNaN(date.getTime())) throw new Error("business.proposals.errors.invalidDate");
|
||||
return date;
|
||||
}
|
||||
|
||||
export async function createProposalRecord(formData: FormData) {
|
||||
const backend = await requireFreelancerBackend();
|
||||
const i18n = new ContentTranslationService(getSqliteConnection().db);
|
||||
const context = i18n.getLocalizationContext(backend.actor);
|
||||
const translations = parseContentTranslationsFromFormData(formData, "proposal", context);
|
||||
backend.service.createProposal(backend.actor, {
|
||||
...payload(formData, translations, context.defaultLocale),
|
||||
translations,
|
||||
});
|
||||
revalidatePath("/business/proposals");
|
||||
}
|
||||
|
||||
export async function updateProposalRecord(formData: FormData) {
|
||||
const backend = await requireFreelancerBackend();
|
||||
const i18n = new ContentTranslationService(getSqliteConnection().db);
|
||||
const context = i18n.getLocalizationContext(backend.actor);
|
||||
const translations = parseContentTranslationsFromFormData(formData, "proposal", context);
|
||||
backend.service.updateProposal(
|
||||
backend.actor,
|
||||
requiredText(formData.get("id"), "business.proposals.errors.notFound"),
|
||||
{
|
||||
...payload(formData, translations, context.defaultLocale),
|
||||
translations,
|
||||
},
|
||||
);
|
||||
revalidatePath("/business/proposals");
|
||||
}
|
||||
|
||||
export async function deleteProposalRecord(formData: FormData) {
|
||||
const { actor, service } = await requireFreelancerBackend();
|
||||
service.deleteProposal(
|
||||
actor,
|
||||
requiredText(formData.get("id"), "business.proposals.errors.deleteNotFound"),
|
||||
);
|
||||
revalidatePath("/business/proposals");
|
||||
}
|
||||
@@ -1,21 +1,59 @@
|
||||
import { requireFreelancerBackend } from "@/server/web/freelancer";
|
||||
import { ProposalsClient, type ProposalRow } from "./proposals-client";
|
||||
import { getSqliteConnection } from "@/server/db/client";
|
||||
import { ContentTranslationService, type ContentTranslationRow } from "@/server/i18n/content";
|
||||
import { resolveFreelancerLocale } from "@/server/i18n/resolver";
|
||||
import { getClientI18nPayload } from "@/server/i18n/translator";
|
||||
import { I18nProvider } from "@/components/i18n/i18n-provider";
|
||||
import { ProposalsClient, type BusinessRelationOption, type ProposalRow } from "./proposals-client";
|
||||
|
||||
export default async function ProposalsPage() {
|
||||
const { actor, service } = await requireFreelancerBackend();
|
||||
const { context, actor, service } = await requireFreelancerBackend();
|
||||
const locale = await resolveFreelancerLocale(context);
|
||||
const content = new ContentTranslationService(getSqliteConnection().db);
|
||||
const localization = content.getLocalizationContext(actor);
|
||||
const clientNames = new Map(service.listClients(actor).map((client) => [client.id, client.name]));
|
||||
const projectNames = new Map(service.listProjects(actor).map((project) => [project.id, project.name]));
|
||||
const proposals: ProposalRow[] = service.listProposals(actor).map((proposal) => ({
|
||||
id: proposal.id,
|
||||
title: proposal.title,
|
||||
amount: proposal.amountMinor / 100,
|
||||
currency: proposal.currency,
|
||||
status: proposal.status,
|
||||
valid_until: proposal.validUntil?.toISOString() ?? null,
|
||||
created_at: proposal.createdAt.toISOString(),
|
||||
clientName: proposal.clientId ? clientNames.get(proposal.clientId) ?? null : null,
|
||||
projectName: proposal.projectId ? projectNames.get(proposal.projectId) ?? null : null,
|
||||
}));
|
||||
const rawProposals = service.listProposals(actor);
|
||||
const translations = content.listBatch("proposal", rawProposals.map((proposal) => proposal.id));
|
||||
const proposals: ProposalRow[] = rawProposals.map((proposal) => {
|
||||
const translationRows = translations.get(proposal.id) ?? [];
|
||||
const resolved = content.resolveEntity("proposal", proposal, {
|
||||
locale: locale.locale,
|
||||
defaultLocale: localization.defaultLocale,
|
||||
translations: translationRows,
|
||||
});
|
||||
|
||||
return <ProposalsClient proposals={proposals} />;
|
||||
return {
|
||||
id: proposal.id,
|
||||
title: resolved.title,
|
||||
description: resolved.description,
|
||||
amount: proposal.amountMinor / 100,
|
||||
currency: proposal.currency,
|
||||
status: proposal.status,
|
||||
valid_until: proposal.validUntil?.toISOString() ?? null,
|
||||
client_id: proposal.clientId,
|
||||
project_id: proposal.projectId,
|
||||
created_at: proposal.createdAt.toISOString(),
|
||||
clientName: proposal.clientId ? clientNames.get(proposal.clientId) ?? null : null,
|
||||
projectName: proposal.projectId ? projectNames.get(proposal.projectId) ?? null : null,
|
||||
translations: toLocalizedValues(translationRows),
|
||||
};
|
||||
});
|
||||
const clients: BusinessRelationOption[] = service.listClients(actor).map((client) => ({ id: client.id, name: client.name }));
|
||||
const projects: BusinessRelationOption[] = service.listProjects(actor).map((project) => ({ id: project.id, name: project.name, client_id: project.clientId }));
|
||||
const i18nPayload = getClientI18nPayload(locale.locale, ["business", "common"]);
|
||||
|
||||
return (
|
||||
<I18nProvider {...i18nPayload}>
|
||||
<ProposalsClient proposals={proposals} clients={clients} projects={projects} localization={localization} />
|
||||
</I18nProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function toLocalizedValues(rows: ContentTranslationRow[]) {
|
||||
return rows.reduce<Record<string, Record<string, string>>>((result, row) => {
|
||||
result[row.locale] = result[row.locale] ?? {};
|
||||
result[row.locale][row.field] = row.value;
|
||||
return result;
|
||||
}, {});
|
||||
}
|
||||
|
||||
@@ -1,85 +1,98 @@
|
||||
"use client";
|
||||
|
||||
import { LocalizedFields, type LocalizedFieldLocale, type LocalizedFieldValues } from "@/components/i18n/localized-fields";
|
||||
import { useTranslations } from "@/components/i18n/i18n-provider";
|
||||
import { contentTranslationRegistry } from "@/lib/i18n/content";
|
||||
import { getDocumentIntlLocale } from "@/lib/i18n/browser";
|
||||
import { createProposalRecord, deleteProposalRecord, updateProposalRecord } from "./actions";
|
||||
import { CheckCircle2, FileEdit, Mail, MoreHorizontal, Plus, Trash2, XCircle } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { format } from "date-fns";
|
||||
import { getDocumentDateFnsLocale } from "@/lib/i18n/date-fns";
|
||||
import { Plus, MoreHorizontal, FileEdit, Trash2, Mail, CheckCircle2, XCircle } from "lucide-react";
|
||||
import { Button, Card, CardContent, Badge } from "poyraz-ui/atoms";
|
||||
import { Badge, Button, Card, CardContent, Input, Label } from "poyraz-ui/atoms";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
toast,
|
||||
} from "poyraz-ui/molecules";
|
||||
|
||||
export type BusinessRelationOption = {
|
||||
id: string;
|
||||
name: string;
|
||||
client_id?: string | null;
|
||||
};
|
||||
|
||||
export type ProposalRow = {
|
||||
id: string;
|
||||
title: string;
|
||||
description: string | null;
|
||||
amount: number;
|
||||
currency: string;
|
||||
status: "draft" | "sent" | "accepted" | "rejected";
|
||||
valid_until: string | null;
|
||||
client_id: string | null;
|
||||
project_id: string | null;
|
||||
clientName: string | null;
|
||||
projectName: string | null;
|
||||
created_at: string;
|
||||
translations?: LocalizedFieldValues;
|
||||
};
|
||||
|
||||
export function ProposalsClient({ proposals }: { proposals: ProposalRow[] }) {
|
||||
const [isAddModalOpen, setIsAddModalOpen] = useState(false);
|
||||
|
||||
const formatCurrency = (amount: number, currency: string) => {
|
||||
return new Intl.NumberFormat(getDocumentIntlLocale(), { style: "currency", currency }).format(amount);
|
||||
type ProposalsClientProps = {
|
||||
proposals: ProposalRow[];
|
||||
clients: BusinessRelationOption[];
|
||||
projects: BusinessRelationOption[];
|
||||
localization: {
|
||||
defaultLocale: string;
|
||||
locales: LocalizedFieldLocale[];
|
||||
};
|
||||
};
|
||||
|
||||
const getStatusBadge = (status: string) => {
|
||||
switch (status) {
|
||||
case "draft":
|
||||
return <Badge variant="secondary">Taslak</Badge>;
|
||||
case "sent":
|
||||
return <Badge className="bg-blue-500/10 text-blue-500 border-blue-500/20 hover:bg-blue-500/20">Gönderildi</Badge>;
|
||||
case "accepted":
|
||||
return <Badge className="bg-emerald-500/10 text-emerald-500 border-emerald-500/20 hover:bg-emerald-500/20">Kabul Edildi</Badge>;
|
||||
case "rejected":
|
||||
return <Badge variant="destructive">Reddedildi</Badge>;
|
||||
default:
|
||||
return <Badge variant="outline">{status}</Badge>;
|
||||
}
|
||||
};
|
||||
const proposalStatuses = ["draft", "sent", "accepted", "rejected"] as const;
|
||||
const currencyOptions = ["TRY", "USD", "EUR", "GBP"] as const;
|
||||
|
||||
export function ProposalsClient({ proposals, clients, projects, localization }: ProposalsClientProps) {
|
||||
const t = useTranslations();
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6 w-full animate-in fade-in slide-in-from-bottom-4 duration-500">
|
||||
{/* Header */}
|
||||
<div className="flex w-full flex-col gap-6 animate-in fade-in slide-in-from-bottom-4 duration-500">
|
||||
<div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold tracking-tight text-foreground">Teklifler</h1>
|
||||
</div>
|
||||
<Button variant="default" effect="shine" onClick={() => setIsAddModalOpen(true)} className="gap-2">
|
||||
<Plus className="h-4 w-4" /> Yeni Teklif
|
||||
</Button>
|
||||
<h1 className="text-3xl font-bold tracking-tight text-foreground">{t("business.proposals.title")}</h1>
|
||||
<ProposalDialog mode="create" clients={clients} projects={projects} localization={localization} />
|
||||
</div>
|
||||
|
||||
{/* List */}
|
||||
<Card>
|
||||
<CardContent className="p-0">
|
||||
<div className="rounded-md border border-border">
|
||||
<div className="rounded-sm border border-border">
|
||||
<div className="relative w-full overflow-auto">
|
||||
<table className="w-full caption-bottom text-sm">
|
||||
<thead className="[&_tr]:border-b">
|
||||
<tr className="border-b border-border transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted">
|
||||
<th className="h-12 px-4 text-left align-middle font-medium text-muted-foreground">Teklif Adı</th>
|
||||
<th className="h-12 px-4 text-left align-middle font-medium text-muted-foreground">Müşteri</th>
|
||||
<th className="h-12 px-4 text-left align-middle font-medium text-muted-foreground">Tutar</th>
|
||||
<th className="h-12 px-4 text-left align-middle font-medium text-muted-foreground">Durum</th>
|
||||
<th className="h-12 px-4 text-left align-middle font-medium text-muted-foreground">Geçerlilik</th>
|
||||
<th className="h-12 px-4 text-right align-middle font-medium text-muted-foreground">İşlemler</th>
|
||||
<tr className="border-b border-border transition-colors hover:bg-muted/50">
|
||||
<TableHead>{t("business.proposals.table.title")}</TableHead>
|
||||
<TableHead>{t("business.common.client")}</TableHead>
|
||||
<TableHead>{t("business.common.amount")}</TableHead>
|
||||
<TableHead>{t("business.common.status")}</TableHead>
|
||||
<TableHead>{t("business.proposals.table.validUntil")}</TableHead>
|
||||
<TableHead className="text-right">{t("business.common.actions")}</TableHead>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="[&_tr:last-child]:border-0">
|
||||
{proposals.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={6} className="h-24 text-center text-muted-foreground">
|
||||
Henüz hiç teklif bulunmuyor.
|
||||
<td colSpan={6} className="h-32 text-center text-muted-foreground">
|
||||
{t("business.proposals.empty")}
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
@@ -87,48 +100,16 @@ export function ProposalsClient({ proposals }: { proposals: ProposalRow[] }) {
|
||||
<tr key={proposal.id} className="border-b border-border transition-colors hover:bg-muted/50">
|
||||
<td className="p-4 align-middle font-medium text-foreground">
|
||||
{proposal.title}
|
||||
{proposal.projectName && (
|
||||
<div className="text-xs text-muted-foreground font-normal mt-0.5">{proposal.projectName}</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="p-4 align-middle text-muted-foreground">
|
||||
{proposal.clientName || "-"}
|
||||
</td>
|
||||
<td className="p-4 align-middle font-medium">
|
||||
{formatCurrency(proposal.amount, proposal.currency)}
|
||||
</td>
|
||||
<td className="p-4 align-middle">
|
||||
{getStatusBadge(proposal.status)}
|
||||
</td>
|
||||
<td className="p-4 align-middle text-muted-foreground">
|
||||
{proposal.valid_until ? format(new Date(proposal.valid_until), "dd MMM yyyy", { locale: getDocumentDateFnsLocale() }) : "-"}
|
||||
{proposal.projectName ? (
|
||||
<div className="mt-0.5 text-xs font-normal text-muted-foreground">{proposal.projectName}</div>
|
||||
) : null}
|
||||
</td>
|
||||
<td className="p-4 align-middle text-muted-foreground">{proposal.clientName || "-"}</td>
|
||||
<td className="p-4 align-middle font-medium">{formatCurrency(proposal.amount, proposal.currency)}</td>
|
||||
<td className="p-4 align-middle"><ProposalStatusBadge status={proposal.status} /></td>
|
||||
<td className="p-4 align-middle text-muted-foreground">{proposal.valid_until ? formatDate(proposal.valid_until) : "-"}</td>
|
||||
<td className="p-4 align-middle text-right">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button size="icon-sm" effect="shine" variant="secondary" >
|
||||
<span className="sr-only">Menüyü aç</span>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem className="cursor-pointer">
|
||||
<FileEdit className="mr-2 h-4 w-4" /> Düzenle
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem className="cursor-pointer">
|
||||
<Mail className="mr-2 h-4 w-4" /> Gönder
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem className="cursor-pointer text-emerald-500 focus:text-emerald-500">
|
||||
<CheckCircle2 className="mr-2 h-4 w-4" /> Kabul Edildi
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem className="cursor-pointer text-destructive focus:text-destructive">
|
||||
<XCircle className="mr-2 h-4 w-4" /> Reddedildi
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem className="cursor-pointer text-destructive focus:text-destructive">
|
||||
<Trash2 className="mr-2 h-4 w-4" /> Sil
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<ProposalMenu proposal={proposal} clients={clients} projects={projects} localization={localization} />
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
@@ -139,21 +120,180 @@ export function ProposalsClient({ proposals }: { proposals: ProposalRow[] }) {
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Add Modal Placeholder */}
|
||||
{isAddModalOpen && (
|
||||
<div className="fixed inset-0 z-50 bg-background/80 backdrop-blur-sm flex items-center justify-center">
|
||||
<Card className="w-full max-w-md">
|
||||
<CardContent className="p-6">
|
||||
<h3 className="text-lg font-bold mb-4 text-foreground">Yeni Teklif Ekle</h3>
|
||||
<p className="text-sm text-muted-foreground mb-6">Bu özellik şu an geliştirme aşamasındadır.</p>
|
||||
<div className="flex justify-end">
|
||||
<Button effect="shine" variant="secondary" onClick={() => setIsAddModalOpen(false)}>Kapat</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ProposalMenu({ proposal, clients, projects, localization }: {
|
||||
proposal: ProposalRow;
|
||||
clients: BusinessRelationOption[];
|
||||
projects: BusinessRelationOption[];
|
||||
localization: ProposalsClientProps["localization"];
|
||||
}) {
|
||||
const t = useTranslations();
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button size="icon-sm" effect="shine" variant="secondary">
|
||||
<span className="sr-only">{t("business.common.openMenu")}</span>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<ProposalDialog mode="edit" proposal={proposal} clients={clients} projects={projects} localization={localization} trigger="menu" />
|
||||
<DropdownMenuItem className="cursor-pointer">
|
||||
<Mail className="mr-2 h-4 w-4" /> {t("business.proposals.actions.send")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem className="cursor-pointer text-emerald-500 focus:text-emerald-500">
|
||||
<CheckCircle2 className="mr-2 h-4 w-4" /> {t("business.proposals.status.accepted")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem className="cursor-pointer text-destructive focus:text-destructive">
|
||||
<XCircle className="mr-2 h-4 w-4" /> {t("business.proposals.status.rejected")}
|
||||
</DropdownMenuItem>
|
||||
<form action={deleteProposalRecord}>
|
||||
<input type="hidden" name="id" value={proposal.id} />
|
||||
<button type="submit" className="flex w-full cursor-pointer items-center px-2 py-1.5 text-sm text-destructive">
|
||||
<Trash2 className="mr-2 h-4 w-4" /> {t("business.common.delete")}
|
||||
</button>
|
||||
</form>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
}
|
||||
|
||||
function ProposalDialog({ mode, proposal, clients, projects, localization, trigger = "button" }: {
|
||||
mode: "create" | "edit";
|
||||
proposal?: ProposalRow;
|
||||
clients: BusinessRelationOption[];
|
||||
projects: BusinessRelationOption[];
|
||||
localization: ProposalsClientProps["localization"];
|
||||
trigger?: "button" | "menu";
|
||||
}) {
|
||||
const t = useTranslations();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const action = mode === "create" ? createProposalRecord : updateProposalRecord;
|
||||
|
||||
async function handleSubmit(formData: FormData) {
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
await action(formData);
|
||||
setOpen(false);
|
||||
toast.success(t(mode === "create" ? "business.proposals.messages.created" : "business.proposals.messages.updated"));
|
||||
} catch (error) {
|
||||
toast.error(resolveTranslatedError(t, error, "business.proposals.errors.saveFailed"));
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
{trigger === "menu" ? (
|
||||
<button type="button" className="flex w-full cursor-pointer items-center px-2 py-1.5 text-sm">
|
||||
<FileEdit className="mr-2 h-4 w-4" /> {t("business.common.edit")}
|
||||
</button>
|
||||
) : (
|
||||
<Button variant="default" effect="shine" className="gap-2">
|
||||
<Plus className="h-4 w-4" /> {t("business.proposals.actions.add")}
|
||||
</Button>
|
||||
)}
|
||||
</DialogTrigger>
|
||||
<DialogContent className="flex max-h-[calc(100dvh-2rem)] w-[calc(100vw-2rem)] flex-col overflow-hidden p-0 sm:max-h-[min(720px,calc(100dvh-4rem))] sm:max-w-2xl">
|
||||
<form action={handleSubmit} className="flex min-h-0 flex-1 flex-col overflow-hidden">
|
||||
{proposal ? <input type="hidden" name="id" value={proposal.id} /> : null}
|
||||
<DialogHeader className="shrink-0 px-5 pb-4 pt-5 pr-12">
|
||||
<DialogTitle>{t(mode === "create" ? "business.proposals.form.createTitle" : "business.proposals.form.editTitle")}</DialogTitle>
|
||||
<DialogDescription>{t("business.proposals.form.description")}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="tiny-scrollbar min-h-0 flex-1 overflow-y-auto px-5 pb-5">
|
||||
<div className="grid gap-4">
|
||||
<LocalizedFields
|
||||
idPrefix={`proposal-${proposal?.id || "new"}`}
|
||||
defaultLocale={localization.defaultLocale}
|
||||
locales={localization.locales}
|
||||
fields={contentTranslationRegistry.proposal.map((field) => ({
|
||||
...field,
|
||||
label: t(`business.proposals.fields.${field.name}`),
|
||||
placeholder: "placeholder" in field && typeof field.placeholder === "string"
|
||||
? t(`business.proposals.placeholders.${field.name}`)
|
||||
: undefined,
|
||||
}))}
|
||||
values={proposal?.translations}
|
||||
fallbackValues={{ title: proposal?.title, description: proposal?.description }}
|
||||
/>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<SelectField name="client_id" label={t("business.common.client")} defaultValue={proposal?.client_id || "__none"}>
|
||||
<SelectItem value="__none">{t("business.common.none")}</SelectItem>
|
||||
{clients.map((client) => <SelectItem key={client.id} value={client.id}>{client.name}</SelectItem>)}
|
||||
</SelectField>
|
||||
<SelectField name="project_id" label={t("business.common.project")} defaultValue={proposal?.project_id || "__none"}>
|
||||
<SelectItem value="__none">{t("business.common.none")}</SelectItem>
|
||||
{projects.map((project) => <SelectItem key={project.id} value={project.id}>{project.name}</SelectItem>)}
|
||||
</SelectField>
|
||||
</div>
|
||||
<div className="grid gap-4 md:grid-cols-4">
|
||||
<Field label={t("business.common.amount")}><Input name="amount" type="number" min="0" step="0.01" required defaultValue={proposal?.amount ?? ""} /></Field>
|
||||
<SelectField name="currency" label={t("business.common.currency")} defaultValue={proposal?.currency || "TRY"}>
|
||||
{currencyOptions.map((currency) => <SelectItem key={currency} value={currency}>{currency}</SelectItem>)}
|
||||
</SelectField>
|
||||
<SelectField name="status" label={t("business.common.status")} defaultValue={proposal?.status || "draft"}>
|
||||
{proposalStatuses.map((status) => <SelectItem key={status} value={status}>{t(`business.proposals.status.${status}`)}</SelectItem>)}
|
||||
</SelectField>
|
||||
<Field label={t("business.proposals.fields.validUntil")}><Input name="valid_until" type="date" defaultValue={proposal?.valid_until?.slice(0, 10) ?? ""} /></Field>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter className="shrink-0 border-t border-border bg-background p-5">
|
||||
<Button variant="default" effect="shine" type="submit" disabled={isSubmitting} className="w-full sm:w-auto">
|
||||
{isSubmitting ? t("business.common.saving") : t(mode === "create" ? "business.proposals.form.submitCreate" : "business.proposals.form.submitEdit")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function ProposalStatusBadge({ status }: { status: ProposalRow["status"] }) {
|
||||
const t = useTranslations();
|
||||
if (status === "draft") return <Badge variant="secondary">{t("business.proposals.status.draft")}</Badge>;
|
||||
if (status === "sent") return <Badge className="border-blue-500/20 bg-blue-500/10 text-blue-500">{t("business.proposals.status.sent")}</Badge>;
|
||||
if (status === "accepted") return <Badge className="border-emerald-500/20 bg-emerald-500/10 text-emerald-500">{t("business.proposals.status.accepted")}</Badge>;
|
||||
return <Badge variant="destructive">{t("business.proposals.status.rejected")}</Badge>;
|
||||
}
|
||||
|
||||
function TableHead({ className = "", children }: { className?: string; children: React.ReactNode }) {
|
||||
return <th className={`h-12 px-4 text-left align-middle font-medium text-muted-foreground ${className}`}>{children}</th>;
|
||||
}
|
||||
|
||||
function Field({ label, children }: { label: string; children: React.ReactNode }) {
|
||||
return <div className="grid gap-2"><Label>{label}</Label>{children}</div>;
|
||||
}
|
||||
|
||||
function SelectField({ name, label, defaultValue, children }: { name: string; label: string; defaultValue: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<Field label={label}>
|
||||
<Select name={name} defaultValue={defaultValue}>
|
||||
<SelectTrigger><SelectValue placeholder={label} /></SelectTrigger>
|
||||
<SelectContent>{children}</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
);
|
||||
}
|
||||
|
||||
function formatCurrency(amount: number, currency: string) {
|
||||
return new Intl.NumberFormat(getDocumentIntlLocale(), { style: "currency", currency }).format(amount);
|
||||
}
|
||||
|
||||
function formatDate(value: string) {
|
||||
return new Intl.DateTimeFormat(getDocumentIntlLocale(), { day: "2-digit", month: "short", year: "numeric" }).format(new Date(value));
|
||||
}
|
||||
|
||||
function resolveTranslatedError(t: ReturnType<typeof useTranslations>, error: unknown, fallbackKey: string) {
|
||||
if (!(error instanceof Error)) return t(fallbackKey);
|
||||
if (/^business\./.test(error.message)) return t(error.message);
|
||||
return error.message || t(fallbackKey);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { getSqliteConnection } from "@/server/db/client";
|
||||
import { ContentTranslationService, parseContentTranslationsFromFormData } from "@/server/i18n/content";
|
||||
import { cleanText, requiredText } from "@/server/web/form-data";
|
||||
import { requireFreelancerBackend } from "@/server/web/freelancer";
|
||||
|
||||
const CYCLES = ["weekly", "monthly", "yearly"] as const;
|
||||
const STATUSES = ["active", "cancelled"] as const;
|
||||
|
||||
function enumValue<T extends readonly string[]>(value: FormDataEntryValue | null, values: T, fallback: T[number]): T[number] {
|
||||
return typeof value === "string" && values.includes(value) ? value as T[number] : fallback;
|
||||
}
|
||||
|
||||
function payload(formData: FormData, translations: Record<string, Record<string, string | null>>, defaultLocale: string) {
|
||||
const amountMinor = amountToMinor(formData.get("amount"));
|
||||
if (amountMinor == null) throw new Error("business.subscriptions.errors.amountRequired");
|
||||
const localized = translations[defaultLocale] ?? {};
|
||||
|
||||
return {
|
||||
name: localized.name ?? "",
|
||||
category: localized.category ?? null,
|
||||
amountMinor,
|
||||
currency: cleanText(formData.get("currency")) ?? "TRY",
|
||||
billingCycle: enumValue(formData.get("billing_cycle"), CYCLES, "monthly"),
|
||||
nextBillingDate: cleanText(formData.get("next_billing_date")),
|
||||
status: enumValue(formData.get("status"), STATUSES, "active"),
|
||||
};
|
||||
}
|
||||
|
||||
function amountToMinor(value: FormDataEntryValue | null) {
|
||||
const normalized = typeof value === "string" ? value.trim().replace(",", ".") : "";
|
||||
if (!normalized) return null;
|
||||
const amount = Number(normalized);
|
||||
if (!Number.isFinite(amount) || amount < 0) throw new Error("business.subscriptions.errors.amountRequired");
|
||||
return Math.round((amount + Number.EPSILON) * 100);
|
||||
}
|
||||
|
||||
export async function createSubscriptionRecord(formData: FormData) {
|
||||
const backend = await requireFreelancerBackend();
|
||||
const i18n = new ContentTranslationService(getSqliteConnection().db);
|
||||
const context = i18n.getLocalizationContext(backend.actor);
|
||||
const translations = parseContentTranslationsFromFormData(formData, "subscription", context);
|
||||
backend.service.createSubscription(backend.actor, {
|
||||
...payload(formData, translations, context.defaultLocale),
|
||||
translations,
|
||||
});
|
||||
revalidatePath("/business/subscriptions");
|
||||
}
|
||||
|
||||
export async function updateSubscriptionRecord(formData: FormData) {
|
||||
const backend = await requireFreelancerBackend();
|
||||
const i18n = new ContentTranslationService(getSqliteConnection().db);
|
||||
const context = i18n.getLocalizationContext(backend.actor);
|
||||
const translations = parseContentTranslationsFromFormData(formData, "subscription", context);
|
||||
backend.service.updateSubscription(
|
||||
backend.actor,
|
||||
requiredText(formData.get("id"), "business.subscriptions.errors.notFound"),
|
||||
{
|
||||
...payload(formData, translations, context.defaultLocale),
|
||||
translations,
|
||||
},
|
||||
);
|
||||
revalidatePath("/business/subscriptions");
|
||||
}
|
||||
|
||||
export async function deleteSubscriptionRecord(formData: FormData) {
|
||||
const { actor, service } = await requireFreelancerBackend();
|
||||
service.deleteSubscription(
|
||||
actor,
|
||||
requiredText(formData.get("id"), "business.subscriptions.errors.deleteNotFound"),
|
||||
);
|
||||
revalidatePath("/business/subscriptions");
|
||||
}
|
||||
@@ -1,19 +1,52 @@
|
||||
import { requireFreelancerBackend } from "@/server/web/freelancer";
|
||||
import { getSqliteConnection } from "@/server/db/client";
|
||||
import { ContentTranslationService, type ContentTranslationRow } from "@/server/i18n/content";
|
||||
import { resolveFreelancerLocale } from "@/server/i18n/resolver";
|
||||
import { getClientI18nPayload } from "@/server/i18n/translator";
|
||||
import { I18nProvider } from "@/components/i18n/i18n-provider";
|
||||
import { SubscriptionsClient, type SubscriptionRow } from "./subscriptions-client";
|
||||
|
||||
export default async function SubscriptionsPage() {
|
||||
const { actor, service } = await requireFreelancerBackend();
|
||||
const subscriptions: SubscriptionRow[] = service.listSubscriptions(actor).map((subscription) => ({
|
||||
id: subscription.id,
|
||||
name: subscription.name,
|
||||
amount: subscription.amountMinor / 100,
|
||||
currency: subscription.currency,
|
||||
billing_cycle: subscription.billingCycle,
|
||||
status: subscription.status,
|
||||
category: subscription.category,
|
||||
next_billing_date: subscription.nextBillingDate,
|
||||
created_at: subscription.createdAt.toISOString(),
|
||||
}));
|
||||
const { context, actor, service } = await requireFreelancerBackend();
|
||||
const locale = await resolveFreelancerLocale(context);
|
||||
const content = new ContentTranslationService(getSqliteConnection().db);
|
||||
const localization = content.getLocalizationContext(actor);
|
||||
const rawSubscriptions = service.listSubscriptions(actor);
|
||||
const translations = content.listBatch("subscription", rawSubscriptions.map((subscription) => subscription.id));
|
||||
const subscriptions: SubscriptionRow[] = rawSubscriptions.map((subscription) => {
|
||||
const translationRows = translations.get(subscription.id) ?? [];
|
||||
const resolved = content.resolveEntity("subscription", subscription, {
|
||||
locale: locale.locale,
|
||||
defaultLocale: localization.defaultLocale,
|
||||
translations: translationRows,
|
||||
});
|
||||
|
||||
return <SubscriptionsClient subscriptions={subscriptions} />;
|
||||
return {
|
||||
id: subscription.id,
|
||||
name: resolved.name,
|
||||
amount: subscription.amountMinor / 100,
|
||||
currency: subscription.currency,
|
||||
billing_cycle: subscription.billingCycle,
|
||||
status: subscription.status,
|
||||
category: resolved.category,
|
||||
next_billing_date: subscription.nextBillingDate,
|
||||
created_at: subscription.createdAt.toISOString(),
|
||||
translations: toLocalizedValues(translationRows),
|
||||
};
|
||||
});
|
||||
const i18nPayload = getClientI18nPayload(locale.locale, ["business", "common"]);
|
||||
|
||||
return (
|
||||
<I18nProvider {...i18nPayload}>
|
||||
<SubscriptionsClient subscriptions={subscriptions} localization={localization} />
|
||||
</I18nProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function toLocalizedValues(rows: ContentTranslationRow[]) {
|
||||
return rows.reduce<Record<string, Record<string, string>>>((result, row) => {
|
||||
result[row.locale] = result[row.locale] ?? {};
|
||||
result[row.locale][row.field] = row.value;
|
||||
return result;
|
||||
}, {});
|
||||
}
|
||||
|
||||
@@ -1,16 +1,31 @@
|
||||
"use client";
|
||||
|
||||
import { LocalizedFields, type LocalizedFieldLocale, type LocalizedFieldValues } from "@/components/i18n/localized-fields";
|
||||
import { useTranslations } from "@/components/i18n/i18n-provider";
|
||||
import { contentTranslationRegistry } from "@/lib/i18n/content";
|
||||
import { getDocumentIntlLocale } from "@/lib/i18n/browser";
|
||||
import { createSubscriptionRecord, deleteSubscriptionRecord, updateSubscriptionRecord } from "./actions";
|
||||
import { CreditCard, FileEdit, MoreHorizontal, Plus, RefreshCw, StopCircle, Trash2 } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { format } from "date-fns";
|
||||
import { getDocumentDateFnsLocale } from "@/lib/i18n/date-fns";
|
||||
import { CreditCard, Plus, MoreHorizontal, FileEdit, Trash2, StopCircle, RefreshCw } from "lucide-react";
|
||||
import { Button, Card, CardContent, Badge } from "poyraz-ui/atoms";
|
||||
import { Badge, Button, Card, CardContent, Input, Label } from "poyraz-ui/atoms";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
toast,
|
||||
} from "poyraz-ui/molecules";
|
||||
|
||||
export type SubscriptionRow = {
|
||||
@@ -23,137 +38,81 @@ export type SubscriptionRow = {
|
||||
category: string | null;
|
||||
next_billing_date: string | null;
|
||||
created_at: string;
|
||||
translations?: LocalizedFieldValues;
|
||||
};
|
||||
|
||||
export function SubscriptionsClient({ subscriptions }: { subscriptions: SubscriptionRow[] }) {
|
||||
const [isAddModalOpen, setIsAddModalOpen] = useState(false);
|
||||
|
||||
const formatCurrency = (amount: number, currency: string) => {
|
||||
return new Intl.NumberFormat(getDocumentIntlLocale(), { style: "currency", currency }).format(amount);
|
||||
type SubscriptionsClientProps = {
|
||||
subscriptions: SubscriptionRow[];
|
||||
localization: {
|
||||
defaultLocale: string;
|
||||
locales: LocalizedFieldLocale[];
|
||||
};
|
||||
};
|
||||
|
||||
const getCycleBadge = (cycle: string) => {
|
||||
switch (cycle) {
|
||||
case "monthly":
|
||||
return "Aylık";
|
||||
case "yearly":
|
||||
return "Yıllık";
|
||||
case "weekly":
|
||||
return "Haftalık";
|
||||
default:
|
||||
return cycle;
|
||||
}
|
||||
};
|
||||
const billingCycles = ["weekly", "monthly", "yearly"] as const;
|
||||
const subscriptionStatuses = ["active", "cancelled"] as const;
|
||||
const currencyOptions = ["TRY", "USD", "EUR", "GBP"] as const;
|
||||
|
||||
export function SubscriptionsClient({ subscriptions, localization }: SubscriptionsClientProps) {
|
||||
const t = useTranslations();
|
||||
const activeMonthlyTotal = subscriptions
|
||||
.filter(s => s.status === "active")
|
||||
.reduce((acc, s) => {
|
||||
let monthlyEquivalent = s.amount;
|
||||
if (s.billing_cycle === "yearly") monthlyEquivalent = s.amount / 12;
|
||||
if (s.billing_cycle === "weekly") monthlyEquivalent = s.amount * 4.33;
|
||||
return acc + monthlyEquivalent;
|
||||
}, 0);
|
||||
.filter((subscription) => subscription.status === "active")
|
||||
.reduce((total, subscription) => total + monthlyEquivalent(subscription), 0);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6 w-full animate-in fade-in slide-in-from-bottom-4 duration-500">
|
||||
<div className="flex w-full flex-col gap-6 animate-in fade-in slide-in-from-bottom-4 duration-500">
|
||||
<div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold tracking-tight text-foreground">Abonelikler ve Masraflar</h1>
|
||||
</div>
|
||||
<Button variant="default" effect="shine" onClick={() => setIsAddModalOpen(true)} className="gap-2">
|
||||
<Plus className="h-4 w-4" /> Yeni Abonelik
|
||||
</Button>
|
||||
<h1 className="text-3xl font-bold tracking-tight text-foreground">{t("business.subscriptions.title")}</h1>
|
||||
<SubscriptionDialog mode="create" localization={localization} />
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
|
||||
<Card className="bg-primary/5 border-primary/20">
|
||||
<div className="grid grid-cols-1 gap-6 md:grid-cols-3">
|
||||
<Card className="border-primary/20 bg-primary/5">
|
||||
<CardContent className="p-6">
|
||||
<div className="flex items-center gap-2 text-primary mb-2">
|
||||
<div className="mb-2 flex items-center gap-2 text-primary">
|
||||
<CreditCard className="h-5 w-5" />
|
||||
<h3 className="font-semibold">Aylık Tahmini Gider</h3>
|
||||
<h3 className="font-semibold">{t("business.subscriptions.stats.monthlyTotal")}</h3>
|
||||
</div>
|
||||
<p className="text-3xl font-bold text-foreground">
|
||||
{formatCurrency(activeMonthlyTotal, "TRY")}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground mt-1">Aktif aboneliklerin aylık ortalaması</p>
|
||||
<p className="text-3xl font-bold text-foreground">{formatCurrency(activeMonthlyTotal, "TRY")}</p>
|
||||
<p className="mt-1 text-sm text-muted-foreground">{t("business.subscriptions.stats.monthlyTotalDesc")}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardContent className="p-0">
|
||||
<div className="rounded-md border border-border">
|
||||
<div className="rounded-sm border border-border">
|
||||
<div className="relative w-full overflow-auto">
|
||||
<table className="w-full caption-bottom text-sm">
|
||||
<thead className="[&_tr]:border-b">
|
||||
<tr className="border-b border-border transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted">
|
||||
<th className="h-12 px-4 text-left align-middle font-medium text-muted-foreground">Abonelik Adı</th>
|
||||
<th className="h-12 px-4 text-left align-middle font-medium text-muted-foreground">Kategori</th>
|
||||
<th className="h-12 px-4 text-left align-middle font-medium text-muted-foreground">Tutar</th>
|
||||
<th className="h-12 px-4 text-left align-middle font-medium text-muted-foreground">Periyot</th>
|
||||
<th className="h-12 px-4 text-left align-middle font-medium text-muted-foreground">Durum</th>
|
||||
<th className="h-12 px-4 text-left align-middle font-medium text-muted-foreground">Sonraki Ödeme</th>
|
||||
<th className="h-12 px-4 text-right align-middle font-medium text-muted-foreground">İşlemler</th>
|
||||
<tr className="border-b border-border transition-colors hover:bg-muted/50">
|
||||
<TableHead>{t("business.subscriptions.table.name")}</TableHead>
|
||||
<TableHead>{t("business.subscriptions.fields.category")}</TableHead>
|
||||
<TableHead>{t("business.common.amount")}</TableHead>
|
||||
<TableHead>{t("business.subscriptions.fields.billingCycle")}</TableHead>
|
||||
<TableHead>{t("business.common.status")}</TableHead>
|
||||
<TableHead>{t("business.subscriptions.fields.nextBillingDate")}</TableHead>
|
||||
<TableHead className="text-right">{t("business.common.actions")}</TableHead>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="[&_tr:last-child]:border-0">
|
||||
{subscriptions.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={7} className="h-24 text-center text-muted-foreground">
|
||||
Henüz hiç abonelik bulunmuyor.
|
||||
<td colSpan={7} className="h-32 text-center text-muted-foreground">
|
||||
{t("business.subscriptions.empty")}
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
subscriptions.map((sub) => (
|
||||
<tr key={sub.id} className={`border-b border-border transition-colors hover:bg-muted/50 ${sub.status === 'cancelled' ? 'opacity-50' : ''}`}>
|
||||
<td className="p-4 align-middle font-medium text-foreground">
|
||||
{sub.name}
|
||||
</td>
|
||||
<td className="p-4 align-middle text-muted-foreground capitalize">
|
||||
{sub.category || "-"}
|
||||
</td>
|
||||
<td className="p-4 align-middle font-medium">
|
||||
{formatCurrency(sub.amount, sub.currency)}
|
||||
</td>
|
||||
<td className="p-4 align-middle text-muted-foreground">
|
||||
{getCycleBadge(sub.billing_cycle)}
|
||||
</td>
|
||||
<td className="p-4 align-middle">
|
||||
{sub.status === "active" ? (
|
||||
<Badge className="bg-emerald-500/10 text-emerald-500 border-emerald-500/20 hover:bg-emerald-500/20">Aktif</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary">İptal Edildi</Badge>
|
||||
)}
|
||||
</td>
|
||||
<td className="p-4 align-middle text-muted-foreground">
|
||||
{sub.next_billing_date ? format(new Date(sub.next_billing_date), "dd MMM yyyy", { locale: getDocumentDateFnsLocale() }) : "-"}
|
||||
</td>
|
||||
subscriptions.map((subscription) => (
|
||||
<tr key={subscription.id} className={`border-b border-border transition-colors hover:bg-muted/50 ${subscription.status === "cancelled" ? "opacity-60" : ""}`}>
|
||||
<td className="p-4 align-middle font-medium text-foreground">{subscription.name}</td>
|
||||
<td className="p-4 align-middle text-muted-foreground">{subscription.category || "-"}</td>
|
||||
<td className="p-4 align-middle font-medium">{formatCurrency(subscription.amount, subscription.currency)}</td>
|
||||
<td className="p-4 align-middle text-muted-foreground">{t(`business.subscriptions.billingCycle.${subscription.billing_cycle}`)}</td>
|
||||
<td className="p-4 align-middle"><SubscriptionStatusBadge status={subscription.status} /></td>
|
||||
<td className="p-4 align-middle text-muted-foreground">{subscription.next_billing_date ? formatDate(subscription.next_billing_date) : "-"}</td>
|
||||
<td className="p-4 align-middle text-right">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button size="icon-sm" effect="shine" variant="secondary" >
|
||||
<span className="sr-only">Menüyü aç</span>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem className="cursor-pointer">
|
||||
<FileEdit className="mr-2 h-4 w-4" /> Düzenle
|
||||
</DropdownMenuItem>
|
||||
{sub.status === "active" ? (
|
||||
<DropdownMenuItem className="cursor-pointer text-amber-500 focus:text-amber-500">
|
||||
<StopCircle className="mr-2 h-4 w-4" /> İptal Et
|
||||
</DropdownMenuItem>
|
||||
) : (
|
||||
<DropdownMenuItem className="cursor-pointer text-emerald-500 focus:text-emerald-500">
|
||||
<RefreshCw className="mr-2 h-4 w-4" /> Yeniden Aktifleştir
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuItem className="cursor-pointer text-destructive focus:text-destructive">
|
||||
<Trash2 className="mr-2 h-4 w-4" /> Sil
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<SubscriptionMenu subscription={subscription} localization={localization} />
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
@@ -164,20 +123,167 @@ export function SubscriptionsClient({ subscriptions }: { subscriptions: Subscrip
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{isAddModalOpen && (
|
||||
<div className="fixed inset-0 z-50 bg-background/80 backdrop-blur-sm flex items-center justify-center">
|
||||
<Card className="w-full max-w-md">
|
||||
<CardContent className="p-6">
|
||||
<h3 className="text-lg font-bold mb-4 text-foreground">Yeni Abonelik Ekle</h3>
|
||||
<p className="text-sm text-muted-foreground mb-6">Bu özellik şu an geliştirme aşamasındadır.</p>
|
||||
<div className="flex justify-end">
|
||||
<Button effect="shine" variant="secondary" onClick={() => setIsAddModalOpen(false)}>Kapat</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SubscriptionMenu({ subscription, localization }: { subscription: SubscriptionRow; localization: SubscriptionsClientProps["localization"] }) {
|
||||
const t = useTranslations();
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button size="icon-sm" effect="shine" variant="secondary">
|
||||
<span className="sr-only">{t("business.common.openMenu")}</span>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<SubscriptionDialog mode="edit" subscription={subscription} localization={localization} trigger="menu" />
|
||||
<DropdownMenuItem className={subscription.status === "active" ? "cursor-pointer text-amber-500 focus:text-amber-500" : "cursor-pointer text-emerald-500 focus:text-emerald-500"}>
|
||||
{subscription.status === "active" ? <StopCircle className="mr-2 h-4 w-4" /> : <RefreshCw className="mr-2 h-4 w-4" />}
|
||||
{subscription.status === "active" ? t("business.subscriptions.actions.cancel") : t("business.subscriptions.actions.reactivate")}
|
||||
</DropdownMenuItem>
|
||||
<form action={deleteSubscriptionRecord}>
|
||||
<input type="hidden" name="id" value={subscription.id} />
|
||||
<button type="submit" className="flex w-full cursor-pointer items-center px-2 py-1.5 text-sm text-destructive">
|
||||
<Trash2 className="mr-2 h-4 w-4" /> {t("business.common.delete")}
|
||||
</button>
|
||||
</form>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
}
|
||||
|
||||
function SubscriptionDialog({ mode, subscription, localization, trigger = "button" }: {
|
||||
mode: "create" | "edit";
|
||||
subscription?: SubscriptionRow;
|
||||
localization: SubscriptionsClientProps["localization"];
|
||||
trigger?: "button" | "menu";
|
||||
}) {
|
||||
const t = useTranslations();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const action = mode === "create" ? createSubscriptionRecord : updateSubscriptionRecord;
|
||||
|
||||
async function handleSubmit(formData: FormData) {
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
await action(formData);
|
||||
setOpen(false);
|
||||
toast.success(t(mode === "create" ? "business.subscriptions.messages.created" : "business.subscriptions.messages.updated"));
|
||||
} catch (error) {
|
||||
toast.error(resolveTranslatedError(t, error, "business.subscriptions.errors.saveFailed"));
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
{trigger === "menu" ? (
|
||||
<button type="button" className="flex w-full cursor-pointer items-center px-2 py-1.5 text-sm">
|
||||
<FileEdit className="mr-2 h-4 w-4" /> {t("business.common.edit")}
|
||||
</button>
|
||||
) : (
|
||||
<Button variant="default" effect="shine" className="gap-2">
|
||||
<Plus className="h-4 w-4" /> {t("business.subscriptions.actions.add")}
|
||||
</Button>
|
||||
)}
|
||||
</DialogTrigger>
|
||||
<DialogContent className="flex max-h-[calc(100dvh-2rem)] w-[calc(100vw-2rem)] flex-col overflow-hidden p-0 sm:max-h-[min(720px,calc(100dvh-4rem))] sm:max-w-2xl">
|
||||
<form action={handleSubmit} className="flex min-h-0 flex-1 flex-col overflow-hidden">
|
||||
{subscription ? <input type="hidden" name="id" value={subscription.id} /> : null}
|
||||
<DialogHeader className="shrink-0 px-5 pb-4 pt-5 pr-12">
|
||||
<DialogTitle>{t(mode === "create" ? "business.subscriptions.form.createTitle" : "business.subscriptions.form.editTitle")}</DialogTitle>
|
||||
<DialogDescription>{t("business.subscriptions.form.description")}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="tiny-scrollbar min-h-0 flex-1 overflow-y-auto px-5 pb-5">
|
||||
<div className="grid gap-4">
|
||||
<LocalizedFields
|
||||
idPrefix={`subscription-${subscription?.id || "new"}`}
|
||||
defaultLocale={localization.defaultLocale}
|
||||
locales={localization.locales}
|
||||
fields={contentTranslationRegistry.subscription.map((field) => ({
|
||||
...field,
|
||||
label: t(`business.subscriptions.fields.${field.name}`),
|
||||
placeholder: "placeholder" in field && typeof field.placeholder === "string"
|
||||
? t(`business.subscriptions.placeholders.${field.name}`)
|
||||
: undefined,
|
||||
}))}
|
||||
values={subscription?.translations}
|
||||
fallbackValues={{ name: subscription?.name, category: subscription?.category }}
|
||||
/>
|
||||
<div className="grid gap-4 md:grid-cols-4">
|
||||
<Field label={t("business.common.amount")}><Input name="amount" type="number" min="0" step="0.01" required defaultValue={subscription?.amount ?? ""} /></Field>
|
||||
<SelectField name="currency" label={t("business.common.currency")} defaultValue={subscription?.currency || "TRY"}>
|
||||
{currencyOptions.map((currency) => <SelectItem key={currency} value={currency}>{currency}</SelectItem>)}
|
||||
</SelectField>
|
||||
<SelectField name="billing_cycle" label={t("business.subscriptions.fields.billingCycle")} defaultValue={subscription?.billing_cycle || "monthly"}>
|
||||
{billingCycles.map((cycle) => <SelectItem key={cycle} value={cycle}>{t(`business.subscriptions.billingCycle.${cycle}`)}</SelectItem>)}
|
||||
</SelectField>
|
||||
<SelectField name="status" label={t("business.common.status")} defaultValue={subscription?.status || "active"}>
|
||||
{subscriptionStatuses.map((status) => <SelectItem key={status} value={status}>{t(`business.subscriptions.status.${status}`)}</SelectItem>)}
|
||||
</SelectField>
|
||||
</div>
|
||||
<Field label={t("business.subscriptions.fields.nextBillingDate")}>
|
||||
<Input name="next_billing_date" type="date" defaultValue={subscription?.next_billing_date ?? ""} />
|
||||
</Field>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter className="shrink-0 border-t border-border bg-background p-5">
|
||||
<Button variant="default" effect="shine" type="submit" disabled={isSubmitting} className="w-full sm:w-auto">
|
||||
{isSubmitting ? t("business.common.saving") : t(mode === "create" ? "business.subscriptions.form.submitCreate" : "business.subscriptions.form.submitEdit")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function SubscriptionStatusBadge({ status }: { status: SubscriptionRow["status"] }) {
|
||||
const t = useTranslations();
|
||||
return status === "active"
|
||||
? <Badge className="border-emerald-500/20 bg-emerald-500/10 text-emerald-500">{t("business.subscriptions.status.active")}</Badge>
|
||||
: <Badge variant="secondary">{t("business.subscriptions.status.cancelled")}</Badge>;
|
||||
}
|
||||
|
||||
function TableHead({ className = "", children }: { className?: string; children: React.ReactNode }) {
|
||||
return <th className={`h-12 px-4 text-left align-middle font-medium text-muted-foreground ${className}`}>{children}</th>;
|
||||
}
|
||||
|
||||
function Field({ label, children }: { label: string; children: React.ReactNode }) {
|
||||
return <div className="grid gap-2"><Label>{label}</Label>{children}</div>;
|
||||
}
|
||||
|
||||
function SelectField({ name, label, defaultValue, children }: { name: string; label: string; defaultValue: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<Field label={label}>
|
||||
<Select name={name} defaultValue={defaultValue}>
|
||||
<SelectTrigger><SelectValue placeholder={label} /></SelectTrigger>
|
||||
<SelectContent>{children}</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
);
|
||||
}
|
||||
|
||||
function monthlyEquivalent(subscription: SubscriptionRow) {
|
||||
if (subscription.billing_cycle === "yearly") return subscription.amount / 12;
|
||||
if (subscription.billing_cycle === "weekly") return subscription.amount * 4.33;
|
||||
return subscription.amount;
|
||||
}
|
||||
|
||||
function formatCurrency(amount: number, currency: string) {
|
||||
return new Intl.NumberFormat(getDocumentIntlLocale(), { style: "currency", currency }).format(amount);
|
||||
}
|
||||
|
||||
function formatDate(value: string) {
|
||||
return new Intl.DateTimeFormat(getDocumentIntlLocale(), { day: "2-digit", month: "short", year: "numeric" }).format(new Date(`${value}T00:00:00`));
|
||||
}
|
||||
|
||||
function resolveTranslatedError(t: ReturnType<typeof useTranslations>, error: unknown, fallbackKey: string) {
|
||||
if (!(error instanceof Error)) return t(fallbackKey);
|
||||
if (/^business\./.test(error.message)) return t(error.message);
|
||||
return error.message || t(fallbackKey);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { getSqliteConnection } from "@/server/db/client";
|
||||
import {
|
||||
ContentTranslationService,
|
||||
parseContentTranslationsFromFormData,
|
||||
} from "@/server/i18n/content";
|
||||
import { cleanText, decimalToMinor, requiredText } from "@/server/web/form-data";
|
||||
import { requireFreelancerBackend } from "@/server/web/freelancer";
|
||||
|
||||
@@ -11,19 +16,20 @@ function enumValue<T extends readonly string[]>(value: FormDataEntryValue | null
|
||||
return typeof value === "string" && values.includes(value) ? value as T[number] : fallback;
|
||||
}
|
||||
|
||||
function payload(formData: FormData) {
|
||||
function payload(formData: FormData, translations?: Record<string, Record<string, string | null>>, defaultLocale = "tr") {
|
||||
const amountMinor = decimalToMinor(formData.get("amount"));
|
||||
if (amountMinor == null) throw new Error("Tutar zorunludur.");
|
||||
if (amountMinor == null) throw new Error("finance.errors.amountRequired");
|
||||
const localized = translations?.[defaultLocale] ?? {};
|
||||
return {
|
||||
type: enumValue(formData.get("type"), TYPES, "expense"),
|
||||
amountMinor,
|
||||
currency: cleanText(formData.get("currency")) ?? "USD",
|
||||
transactionDate: cleanText(formData.get("transaction_date")) ?? new Date().toISOString().slice(0, 10),
|
||||
category: cleanText(formData.get("category")),
|
||||
category: localized.category ?? cleanText(formData.get("category")),
|
||||
paymentStatus: enumValue(formData.get("payment_status"), STATUSES, "planned"),
|
||||
clientId: cleanText(formData.get("client_id")),
|
||||
projectId: cleanText(formData.get("project_id")),
|
||||
description: cleanText(formData.get("description")),
|
||||
description: localized.description ?? cleanText(formData.get("description")),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -38,9 +44,13 @@ function completeRelations(
|
||||
|
||||
export async function createFinanceTransactionRecord(formData: FormData) {
|
||||
const backend = await requireFreelancerBackend();
|
||||
const i18n = new ContentTranslationService(getSqliteConnection().db);
|
||||
const context = i18n.getLocalizationContext(backend.actor);
|
||||
const translations = parseContentTranslationsFromFormData(formData, "finance_transaction", context);
|
||||
const data = payload(formData, translations, context.defaultLocale);
|
||||
backend.service.createFinanceTransaction(
|
||||
backend.actor,
|
||||
completeRelations(payload(formData), backend.service, backend.actor),
|
||||
{ ...completeRelations(data, backend.service, backend.actor), translations },
|
||||
);
|
||||
revalidatePath("/finance");
|
||||
revalidatePath("/clients");
|
||||
@@ -49,11 +59,15 @@ export async function createFinanceTransactionRecord(formData: FormData) {
|
||||
|
||||
export async function updateFinanceTransactionRecord(formData: FormData) {
|
||||
const backend = await requireFreelancerBackend();
|
||||
const id = requiredText(formData.get("id"), "Finans kaydı bulunamadı.");
|
||||
const i18n = new ContentTranslationService(getSqliteConnection().db);
|
||||
const context = i18n.getLocalizationContext(backend.actor);
|
||||
const translations = parseContentTranslationsFromFormData(formData, "finance_transaction", context);
|
||||
const id = requiredText(formData.get("id"), "finance.errors.notFound");
|
||||
const data = payload(formData, translations, context.defaultLocale);
|
||||
backend.service.updateFinanceTransaction(
|
||||
backend.actor,
|
||||
id,
|
||||
completeRelations(payload(formData), backend.service, backend.actor),
|
||||
{ ...completeRelations(data, backend.service, backend.actor), translations },
|
||||
);
|
||||
revalidatePath("/finance");
|
||||
revalidatePath("/clients");
|
||||
@@ -64,7 +78,7 @@ export async function deleteFinanceTransactionRecord(formData: FormData) {
|
||||
const { actor, service } = await requireFreelancerBackend();
|
||||
service.deleteFinanceTransaction(
|
||||
actor,
|
||||
requiredText(formData.get("id"), "Silinecek finans kaydı bulunamadı."),
|
||||
requiredText(formData.get("id"), "finance.errors.deleteNotFound"),
|
||||
);
|
||||
revalidatePath("/finance");
|
||||
revalidatePath("/clients");
|
||||
|
||||
@@ -2,12 +2,14 @@
|
||||
|
||||
import { getDocumentIntlLocale } from "@/lib/i18n/browser";
|
||||
import { useTranslations } from "@/components/i18n/i18n-provider";
|
||||
import { LocalizedFields, type LocalizedFieldLocale, type LocalizedFieldValues } from "@/components/i18n/localized-fields";
|
||||
import { contentTranslationRegistry } from "@/lib/i18n/content";
|
||||
import {
|
||||
createFinanceTransactionRecord,
|
||||
deleteFinanceTransactionRecord,
|
||||
updateFinanceTransactionRecord,
|
||||
} from "@/app/(dashboard)/finance/actions";
|
||||
import { Badge, Button, Card, CardContent, Input, Label, Textarea } from "poyraz-ui/atoms";
|
||||
import { Badge, Button, Card, CardContent, Input, Label } from "poyraz-ui/atoms";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
@@ -57,18 +59,7 @@ export type FinanceTransactionItem = {
|
||||
clientName: string | null;
|
||||
projectName: string | null;
|
||||
description: string | null;
|
||||
};
|
||||
|
||||
const typeLabels = {
|
||||
income: "Gelir",
|
||||
expense: "Gider",
|
||||
};
|
||||
|
||||
const paymentStatusLabels = {
|
||||
planned: "Planlandı",
|
||||
pending: "Bekliyor",
|
||||
paid: "Ödendi",
|
||||
cancelled: "İptal edildi",
|
||||
translations?: LocalizedFieldValues;
|
||||
};
|
||||
|
||||
const paymentStatusClasses = {
|
||||
@@ -79,32 +70,34 @@ const paymentStatusClasses = {
|
||||
};
|
||||
|
||||
const currencyOptions = [
|
||||
{ value: "USD", label: "Dolar (USD)" },
|
||||
{ value: "EUR", label: "Euro (EUR)" },
|
||||
{ value: "TRY", label: "Türk lirası (TRY)" },
|
||||
{ value: "GBP", label: "Sterlin (GBP)" },
|
||||
{ value: "CAD", label: "Kanada doları (CAD)" },
|
||||
{ value: "AUD", label: "Avustralya doları (AUD)" },
|
||||
{ value: "USD", labelKey: "finance.currency.usd" },
|
||||
{ value: "EUR", labelKey: "finance.currency.eur" },
|
||||
{ value: "TRY", labelKey: "finance.currency.try" },
|
||||
{ value: "GBP", labelKey: "finance.currency.gbp" },
|
||||
{ value: "CAD", labelKey: "finance.currency.cad" },
|
||||
{ value: "AUD", labelKey: "finance.currency.aud" },
|
||||
];
|
||||
|
||||
// Dizilim ve featured alanı, özet şeridinde hangi metriklerin önce
|
||||
// gösterileceğini tek bir yerden değiştirmeyi sağlar.
|
||||
const financeSummaryCardConfig = [
|
||||
{ key: "afterTax", label: "Vergi Sonrası Net", tone: "green", icon: Wallet, featured: true },
|
||||
{ key: "net", label: "Brüt kazanç", tone: "primary", icon: Wallet, featured: true },
|
||||
{ key: "income", label: "Aylık gelir", tone: "green", icon: ArrowUpRight, featured: false },
|
||||
{ key: "expense", label: "Aylık gider", tone: "rose", icon: ArrowDownRight, featured: false },
|
||||
{ key: "pending", label: "Bekleyen", tone: "amber", icon: Wallet, featured: false },
|
||||
{ key: "tax", label: "KDV Tahmini (%20)", tone: "amber", icon: Wallet, featured: false },
|
||||
{ key: "afterTax", tone: "green", icon: Wallet, featured: true },
|
||||
{ key: "net", tone: "primary", icon: Wallet, featured: true },
|
||||
{ key: "income", tone: "green", icon: ArrowUpRight, featured: false },
|
||||
{ key: "expense", tone: "rose", icon: ArrowDownRight, featured: false },
|
||||
{ key: "pending", tone: "amber", icon: Wallet, featured: false },
|
||||
{ key: "tax", tone: "amber", icon: Wallet, featured: false },
|
||||
] as const;
|
||||
|
||||
type FinanceClientProps = {
|
||||
transactions: FinanceTransactionItem[];
|
||||
clients: FinanceRelationOption[];
|
||||
projects: FinanceRelationOption[];
|
||||
localization: {
|
||||
defaultLocale: string;
|
||||
locales: LocalizedFieldLocale[];
|
||||
};
|
||||
};
|
||||
|
||||
export function FinanceClient({ transactions, clients, projects }: FinanceClientProps) {
|
||||
export function FinanceClient({ transactions, clients, projects, localization }: FinanceClientProps) {
|
||||
const t = useTranslations();
|
||||
const [query, setQuery] = useState("");
|
||||
const [monthFilter, setMonthFilter] = useState(() => new Date().toISOString().slice(0, 7));
|
||||
@@ -120,7 +113,7 @@ export function FinanceClient({ transactions, clients, projects }: FinanceClient
|
||||
transaction.category,
|
||||
transaction.clientName,
|
||||
transaction.projectName,
|
||||
typeLabels[transaction.type],
|
||||
t(`finance.types.${transaction.type}`),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.some((value) => value!.toLowerCase().includes(normalizedQuery)),
|
||||
@@ -131,6 +124,7 @@ export function FinanceClient({ transactions, clients, projects }: FinanceClient
|
||||
const categoryBreakdown = useMemo(() => calculateExpenseCategories(filteredByMonth), [filteredByMonth]);
|
||||
const summaryCards = financeSummaryCardConfig.map((card) => ({
|
||||
...card,
|
||||
label: t(`finance.summary.${card.key}`),
|
||||
value: formatCurrency(summary[card.key]),
|
||||
}));
|
||||
|
||||
@@ -154,7 +148,7 @@ export function FinanceClient({ transactions, clients, projects }: FinanceClient
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<AIFinanceDialog />
|
||||
<FinanceDialog mode="create" clients={clients} projects={projects} />
|
||||
<FinanceDialog mode="create" clients={clients} projects={projects} localization={localization} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -162,10 +156,10 @@ export function FinanceClient({ transactions, clients, projects }: FinanceClient
|
||||
<div className="flex items-end justify-between gap-4">
|
||||
<div>
|
||||
<h2 id="finance-summary-title" className="text-base font-semibold text-foreground">
|
||||
Finans özeti
|
||||
{t("finance.summary.title")}
|
||||
</h2>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Öne çıkan metrikler önce gösterilir; diğer kartlar arasında kaydırarak ilerleyebilirsin.
|
||||
{t("finance.summary.description")}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex shrink-0 gap-2">
|
||||
@@ -174,7 +168,7 @@ export function FinanceClient({ transactions, clients, projects }: FinanceClient
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="icon"
|
||||
aria-label="Önceki finans özet kartları"
|
||||
aria-label={t("finance.summary.previous")}
|
||||
onClick={() => scrollSummary(-1)}
|
||||
>
|
||||
<ChevronLeft className="h-4 w-4" />
|
||||
@@ -184,7 +178,7 @@ export function FinanceClient({ transactions, clients, projects }: FinanceClient
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="icon"
|
||||
aria-label="Sonraki finans özet kartları"
|
||||
aria-label={t("finance.summary.next")}
|
||||
onClick={() => scrollSummary(1)}
|
||||
>
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
@@ -195,7 +189,7 @@ export function FinanceClient({ transactions, clients, projects }: FinanceClient
|
||||
<div
|
||||
ref={summaryTrackRef}
|
||||
role="region"
|
||||
aria-label="Kaydırılabilir finans özeti"
|
||||
aria-label={t("finance.summary.region")}
|
||||
tabIndex={0}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "ArrowLeft") {
|
||||
@@ -228,16 +222,16 @@ export function FinanceClient({ transactions, clients, projects }: FinanceClient
|
||||
<CardContent className="space-y-4 p-4">
|
||||
<div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
|
||||
<div>
|
||||
<h2 className="text-base font-semibold text-foreground">İşlem listesi</h2>
|
||||
<h2 className="text-base font-semibold text-foreground">{t("finance.list.title")}</h2>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{filteredTransactions.length} kayıt görüntüleniyor.
|
||||
{t("finance.list.description", { count: filteredTransactions.length })}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2 sm:flex-row">
|
||||
<Input
|
||||
value={query}
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
placeholder="Kategori, müşteri, proje veya açıklama ara"
|
||||
placeholder={t("finance.list.searchPlaceholder")}
|
||||
className="sm:w-80"
|
||||
/>
|
||||
<Input
|
||||
@@ -253,11 +247,11 @@ export function FinanceClient({ transactions, clients, projects }: FinanceClient
|
||||
<div className="overflow-x-auto rounded-sm border border-border">
|
||||
<div className="min-w-[800px]">
|
||||
<div className="grid grid-cols-[1.4fr_0.8fr_0.8fr_0.8fr_1fr] gap-4 border-b border-border bg-muted/40 px-4 py-3 text-xs font-medium uppercase text-muted-foreground">
|
||||
<span>İşlem</span>
|
||||
<span>Tarih</span>
|
||||
<span>Tutar</span>
|
||||
<span>Durum</span>
|
||||
<span className="text-right">İşlem</span>
|
||||
<span>{t("finance.list.headers.transaction")}</span>
|
||||
<span>{t("finance.list.headers.date")}</span>
|
||||
<span>{t("finance.list.headers.amount")}</span>
|
||||
<span>{t("finance.list.headers.status")}</span>
|
||||
<span className="text-right">{t("finance.list.headers.action")}</span>
|
||||
</div>
|
||||
<div className="divide-y divide-border">
|
||||
{filteredTransactions.map((transaction) => (
|
||||
@@ -266,6 +260,7 @@ export function FinanceClient({ transactions, clients, projects }: FinanceClient
|
||||
transaction={transaction}
|
||||
clients={clients}
|
||||
projects={projects}
|
||||
localization={localization}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
@@ -280,15 +275,19 @@ export function FinanceClient({ transactions, clients, projects }: FinanceClient
|
||||
<Card>
|
||||
<CardContent className="space-y-4 p-4">
|
||||
<div>
|
||||
<h2 className="text-base font-semibold text-foreground">Gider kategorileri</h2>
|
||||
<p className="text-sm text-muted-foreground">Aylık gider dağılımı</p>
|
||||
<h2 className="text-base font-semibold text-foreground">{t("finance.expenseCategories.title")}</h2>
|
||||
<p className="text-sm text-muted-foreground">{t("finance.expenseCategories.description")}</p>
|
||||
</div>
|
||||
{categoryBreakdown.length > 0 ? (
|
||||
<div className="space-y-3">
|
||||
{categoryBreakdown.map((item) => (
|
||||
<div key={item.category} className="space-y-1">
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">{item.category}</span>
|
||||
<span className="text-muted-foreground">
|
||||
{item.category === "__uncategorized"
|
||||
? t("finance.expenseCategories.noCategory")
|
||||
: item.category}
|
||||
</span>
|
||||
<span className="font-medium text-foreground">{formatCurrency(item.amount)}</span>
|
||||
</div>
|
||||
<div className="h-2 rounded-full bg-muted">
|
||||
@@ -301,7 +300,7 @@ export function FinanceClient({ transactions, clients, projects }: FinanceClient
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">Bu ay gider kaydı yok.</p>
|
||||
<p className="text-sm text-muted-foreground">{t("finance.expenseCategories.noExpense")}</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
@@ -314,11 +313,17 @@ function TransactionRow({
|
||||
transaction,
|
||||
clients,
|
||||
projects,
|
||||
localization,
|
||||
}: {
|
||||
transaction: FinanceTransactionItem;
|
||||
clients: FinanceRelationOption[];
|
||||
projects: FinanceRelationOption[];
|
||||
localization: {
|
||||
defaultLocale: string;
|
||||
locales: LocalizedFieldLocale[];
|
||||
};
|
||||
}) {
|
||||
const t = useTranslations();
|
||||
const isIncome = transaction.type === "income";
|
||||
|
||||
return (
|
||||
@@ -329,10 +334,10 @@ function TransactionRow({
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<div className="font-medium text-foreground">
|
||||
{transaction.description || typeLabels[transaction.type]}
|
||||
{transaction.description || t(`finance.types.${transaction.type}`)}
|
||||
</div>
|
||||
<div className="truncate text-sm text-muted-foreground">
|
||||
{transaction.category || "Kategori yok"} · {transaction.projectName || transaction.clientName || "Bağlantı yok"}
|
||||
{transaction.category || t("finance.expenseCategories.noCategory")} · {transaction.projectName || transaction.clientName || t("finance.form.noClient")}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -343,16 +348,16 @@ function TransactionRow({
|
||||
</div>
|
||||
<div>
|
||||
<Badge className={paymentStatusClasses[transaction.payment_status]}>
|
||||
{paymentStatusLabels[transaction.payment_status]}
|
||||
{t(`finance.paymentStatus.${transaction.payment_status}`)}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2">
|
||||
<FinanceDialog mode="edit" transaction={transaction} clients={clients} projects={projects} />
|
||||
<FinanceDialog mode="edit" transaction={transaction} clients={clients} projects={projects} localization={localization} />
|
||||
<form action={deleteFinanceTransactionRecord}>
|
||||
<input type="hidden" name="id" value={transaction.id} />
|
||||
<Button effect="shine" type="submit" variant="secondary" className="gap-2 text-rose-600">
|
||||
<Trash2 className="h-4 w-4" />
|
||||
Sil
|
||||
{t("finance.actions.delete")}
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
@@ -365,12 +370,18 @@ function FinanceDialog({
|
||||
transaction,
|
||||
clients,
|
||||
projects,
|
||||
localization,
|
||||
}: {
|
||||
mode: "create" | "edit";
|
||||
transaction?: FinanceTransactionItem;
|
||||
clients: FinanceRelationOption[];
|
||||
projects: FinanceRelationOption[];
|
||||
localization: {
|
||||
defaultLocale: string;
|
||||
locales: LocalizedFieldLocale[];
|
||||
};
|
||||
}) {
|
||||
const t = useTranslations();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const action = mode === "create" ? createFinanceTransactionRecord : updateFinanceTransactionRecord;
|
||||
@@ -380,13 +391,9 @@ function FinanceDialog({
|
||||
try {
|
||||
await action(formData);
|
||||
setOpen(false);
|
||||
toast.success(mode === "create" ? "İşlem eklendi." : "İşlem güncellendi.");
|
||||
toast.success(mode === "create" ? t("finance.form.messages.createSuccess") : t("finance.form.messages.updateSuccess"));
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Finans işlemi kaydedilirken beklenmeyen bir hata oluştu.",
|
||||
);
|
||||
toast.error(resolveTranslatedError(t, error, "finance.form.messages.error"));
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
@@ -397,23 +404,23 @@ function FinanceDialog({
|
||||
<DialogTrigger asChild>
|
||||
<Button effect="shine" variant={mode === "create" ? "default" : "secondary"} className="gap-2">
|
||||
{mode === "create" ? <Plus className="h-4 w-4" /> : <Pencil className="h-4 w-4" />}
|
||||
{mode === "create" ? "İşlem ekle" : "Düzenle"}
|
||||
{mode === "create" ? t("finance.actions.add") : t("finance.actions.edit")}
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="flex max-h-[calc(100dvh-2rem)] w-[calc(100vw-2rem)] flex-col overflow-hidden p-0 sm:max-h-[min(680px,calc(100dvh-4rem))] sm:max-w-xl data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95">
|
||||
<form action={handleSubmit} className="flex min-h-0 flex-1 flex-col overflow-hidden">
|
||||
{transaction ? <input type="hidden" name="id" value={transaction.id} /> : null}
|
||||
<DialogHeader className="shrink-0 px-5 pb-4 pt-5 pr-12">
|
||||
<DialogTitle>{mode === "create" ? "Yeni finans işlemi" : "Finans işlemini düzenle"}</DialogTitle>
|
||||
<DialogDescription>Gelir veya gider kaydını müşteri/proje bağlantısıyla kaydet.</DialogDescription>
|
||||
<DialogTitle>{mode === "create" ? t("finance.form.createTitle") : t("finance.form.editTitle")}</DialogTitle>
|
||||
<DialogDescription>{t("finance.form.description")}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="tiny-scrollbar min-h-0 flex-1 overflow-y-auto px-5 pb-5">
|
||||
<FinanceFormFields transaction={transaction} clients={clients} projects={projects} />
|
||||
<FinanceFormFields transaction={transaction} clients={clients} projects={projects} localization={localization} />
|
||||
</div>
|
||||
<DialogFooter className="shrink-0 border-t border-border bg-background p-5">
|
||||
<Button variant="default" effect="shine" type="submit" disabled={isSubmitting} className="w-full gap-2 sm:w-auto">
|
||||
{mode === "create" ? <Plus className="h-4 w-4" /> : <Pencil className="h-4 w-4" />}
|
||||
{isSubmitting ? "Kaydediliyor" : mode === "create" ? "İşlemi ekle" : "Değişiklikleri kaydet"}
|
||||
{isSubmitting ? t("finance.actions.saving") : mode === "create" ? t("finance.form.submitCreate") : t("finance.form.submitEdit")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
@@ -426,11 +433,17 @@ function FinanceFormFields({
|
||||
transaction,
|
||||
clients,
|
||||
projects,
|
||||
localization,
|
||||
}: {
|
||||
transaction?: FinanceTransactionItem;
|
||||
clients: FinanceRelationOption[];
|
||||
projects: FinanceRelationOption[];
|
||||
localization: {
|
||||
defaultLocale: string;
|
||||
locales: LocalizedFieldLocale[];
|
||||
};
|
||||
}) {
|
||||
const t = useTranslations();
|
||||
const [clientId, setClientId] = useState(transaction?.client_id || "__none");
|
||||
const [projectId, setProjectId] = useState(transaction?.project_id || "__none");
|
||||
const selectedProject =
|
||||
@@ -469,32 +482,32 @@ function FinanceFormFields({
|
||||
return (
|
||||
<div className="grid gap-4">
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<SelectField name="type" label="Tip" defaultValue={transaction?.type || "income"}>
|
||||
<SelectItem value="income">Gelir</SelectItem>
|
||||
<SelectItem value="expense">Gider</SelectItem>
|
||||
<SelectField name="type" label={t("finance.form.type")} defaultValue={transaction?.type || "income"}>
|
||||
<SelectItem value="income">{t("finance.types.income")}</SelectItem>
|
||||
<SelectItem value="expense">{t("finance.types.expense")}</SelectItem>
|
||||
</SelectField>
|
||||
<SelectField name="payment_status" label="Ödeme durumu" defaultValue={transaction?.payment_status || "planned"}>
|
||||
<SelectItem value="planned">Planlandı</SelectItem>
|
||||
<SelectItem value="pending">Bekliyor</SelectItem>
|
||||
<SelectItem value="paid">Ödendi</SelectItem>
|
||||
<SelectItem value="cancelled">İptal edildi</SelectItem>
|
||||
<SelectField name="payment_status" label={t("finance.form.paymentStatus")} defaultValue={transaction?.payment_status || "planned"}>
|
||||
<SelectItem value="planned">{t("finance.paymentStatus.planned")}</SelectItem>
|
||||
<SelectItem value="pending">{t("finance.paymentStatus.pending")}</SelectItem>
|
||||
<SelectItem value="paid">{t("finance.paymentStatus.paid")}</SelectItem>
|
||||
<SelectItem value="cancelled">{t("finance.paymentStatus.cancelled")}</SelectItem>
|
||||
</SelectField>
|
||||
</div>
|
||||
<div className="grid gap-4 md:grid-cols-3">
|
||||
<div className="grid gap-2">
|
||||
<Label>Tutar</Label>
|
||||
<Label>{t("finance.form.amount")}</Label>
|
||||
<Input name="amount" type="number" min="0" step="0.01" required defaultValue={transaction?.amount ?? ""} />
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label>Para birimi</Label>
|
||||
<Label>{t("finance.form.currency")}</Label>
|
||||
<Select name="currency" defaultValue={currencyValue}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Para birimi seç" />
|
||||
<SelectValue placeholder={t("finance.form.currencySelect")} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{currencyOptions.map((currency) => (
|
||||
<SelectItem key={currency.value} value={currency.value}>
|
||||
{currency.label}
|
||||
{t(currency.labelKey)}
|
||||
</SelectItem>
|
||||
))}
|
||||
{hasCustomCurrency ? (
|
||||
@@ -504,17 +517,31 @@ function FinanceFormFields({
|
||||
</Select>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label>Tarih</Label>
|
||||
<Label>{t("finance.form.date")}</Label>
|
||||
<Input name="transaction_date" type="date" defaultValue={transaction?.transaction_date || new Date().toISOString().slice(0, 10)} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label>Kategori</Label>
|
||||
<Input name="category" defaultValue={transaction?.category || ""} placeholder="Örn. Yazılım, müşteri ödemesi, vergi" />
|
||||
</div>
|
||||
<LocalizedFields
|
||||
idPrefix={`finance-${transaction?.id || "new"}-cat`}
|
||||
defaultLocale={localization.defaultLocale}
|
||||
locales={localization.locales}
|
||||
fields={contentTranslationRegistry.finance_transaction
|
||||
.filter((f) => f.name === "category")
|
||||
.map((f) => ({
|
||||
...f,
|
||||
label: t(`finance.fields.${f.name}`) || f.label,
|
||||
placeholder: "placeholder" in f && typeof f.placeholder === "string"
|
||||
? t(`finance.placeholders.${f.name}`) || f.placeholder
|
||||
: undefined,
|
||||
}))}
|
||||
values={transaction?.translations}
|
||||
fallbackValues={{
|
||||
category: transaction?.category,
|
||||
}}
|
||||
/>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<div className="grid gap-2">
|
||||
<Label>Müşteri</Label>
|
||||
<Label>{t("finance.form.client")}</Label>
|
||||
{shouldLockClient ? <input type="hidden" name="client_id" value={clientId} /> : null}
|
||||
<Select
|
||||
name="client_id"
|
||||
@@ -523,10 +550,10 @@ function FinanceFormFields({
|
||||
disabled={shouldLockClient}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Müşteri seç" />
|
||||
<SelectValue placeholder={t("finance.form.clientSelect")} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="__none">Müşteri yok</SelectItem>
|
||||
<SelectItem value="__none">{t("finance.form.noClient")}</SelectItem>
|
||||
{clients.map((client) => (
|
||||
<SelectItem key={client.id} value={client.id}>
|
||||
{client.name}
|
||||
@@ -536,13 +563,13 @@ function FinanceFormFields({
|
||||
</Select>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label>Proje</Label>
|
||||
<Label>{t("finance.form.project")}</Label>
|
||||
<Select name="project_id" value={projectId} onValueChange={handleProjectChange}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Proje seç" />
|
||||
<SelectValue placeholder={t("finance.form.projectSelect")} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="__none">Proje yok</SelectItem>
|
||||
<SelectItem value="__none">{t("finance.form.noProject")}</SelectItem>
|
||||
{filteredProjects.map((project) => (
|
||||
<SelectItem key={project.id} value={project.id}>
|
||||
{project.name}
|
||||
@@ -552,10 +579,24 @@ function FinanceFormFields({
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label>Açıklama</Label>
|
||||
<Textarea name="description" defaultValue={transaction?.description || ""} rows={3} />
|
||||
</div>
|
||||
<LocalizedFields
|
||||
idPrefix={`finance-${transaction?.id || "new"}-desc`}
|
||||
defaultLocale={localization.defaultLocale}
|
||||
locales={localization.locales}
|
||||
fields={contentTranslationRegistry.finance_transaction
|
||||
.filter((f) => f.name === "description")
|
||||
.map((f) => ({
|
||||
...f,
|
||||
label: t(`finance.fields.${f.name}`) || f.label,
|
||||
placeholder: "placeholder" in f && typeof f.placeholder === "string"
|
||||
? t(`finance.placeholders.${f.name}`) || f.placeholder
|
||||
: undefined,
|
||||
}))}
|
||||
values={transaction?.translations}
|
||||
fallbackValues={{
|
||||
description: transaction?.description,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -565,7 +606,7 @@ function SelectField({ name, label, defaultValue, children }: { name: string; la
|
||||
<div className="grid gap-2">
|
||||
<Label>{label}</Label>
|
||||
<Select name={name} defaultValue={defaultValue}>
|
||||
<SelectTrigger><SelectValue placeholder={`${label} seç`} /></SelectTrigger>
|
||||
<SelectTrigger><SelectValue placeholder={label} /></SelectTrigger>
|
||||
<SelectContent>{children}</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
@@ -573,16 +614,17 @@ function SelectField({ name, label, defaultValue, children }: { name: string; la
|
||||
}
|
||||
|
||||
function EmptyState({ hasQuery }: { hasQuery: boolean }) {
|
||||
const t = useTranslations();
|
||||
return (
|
||||
<div className="flex min-h-72 flex-col items-center justify-center rounded-sm border border-dashed border-border bg-muted/20 p-8 text-center">
|
||||
<Wallet className="h-10 w-10 text-muted-foreground" />
|
||||
<h3 className="mt-4 text-lg font-semibold text-foreground">
|
||||
{hasQuery ? "Aramana uygun işlem yok" : "Henüz finans işlemi eklenmedi"}
|
||||
{hasQuery ? t("finance.empty.noMatchTitle") : t("finance.empty.noTransactionTitle")}
|
||||
</h3>
|
||||
<p className="mt-2 max-w-md text-sm text-muted-foreground">
|
||||
{hasQuery
|
||||
? "Arama metnini sadeleştirerek tekrar deneyebilirsin."
|
||||
: "İlk gelir veya gider kaydını ekleyerek aylık finans özetini oluşturmaya başlayabilirsin."}
|
||||
? t("finance.empty.noMatchDesc")
|
||||
: t("finance.empty.noTransactionDesc")}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
@@ -633,6 +675,7 @@ function formatMessageContent(text: string) {
|
||||
}
|
||||
|
||||
function AIFinanceDialog() {
|
||||
const t = useTranslations();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [result, setResult] = useState<string | null>(null);
|
||||
@@ -644,12 +687,14 @@ function AIFinanceDialog() {
|
||||
const res = await fetch("/api/finance-analysis", { method: "POST" });
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
throw new Error(data.error || "Bilinmeyen bir hata oluştu.");
|
||||
throw new Error(data.error || t("finance.ai.error"));
|
||||
}
|
||||
setResult(data.text);
|
||||
} catch (error) {
|
||||
setResult(
|
||||
`Hata: ${error instanceof Error ? error.message : "Bilinmeyen bir hata oluştu."}`,
|
||||
t("finance.ai.errorWithReason", {
|
||||
reason: resolveTranslatedError(t, error, "finance.ai.error"),
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
@@ -661,17 +706,17 @@ function AIFinanceDialog() {
|
||||
<DialogTrigger asChild>
|
||||
<Button effect="shine" variant="secondary" className="gap-2">
|
||||
<Brain className="h-4 w-4" />
|
||||
AI Analizi
|
||||
{t("finance.actions.aiAnalysis")}
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="w-[calc(100vw-2rem)] sm:max-w-2xl max-h-[80vh] overflow-y-auto rounded-lg p-6">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Brain className="h-5 w-5 text-indigo-600" />
|
||||
Yapay Zeka Finansal Yorumlama
|
||||
{t("finance.ai.title")}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Son 30 günlük finansal kayıtlarınızı analiz edip size önerilerde bulunuyorum.
|
||||
{t("finance.ai.description")}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
@@ -680,7 +725,7 @@ function AIFinanceDialog() {
|
||||
<div className="text-center py-10">
|
||||
<Button variant="default" effect="shine" onClick={handleAnalyze} className="gap-2">
|
||||
<Brain className="h-4 w-4" />
|
||||
Raporu Oluştur
|
||||
{t("finance.ai.generate")}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
@@ -688,7 +733,7 @@ function AIFinanceDialog() {
|
||||
{loading && (
|
||||
<div className="flex flex-col items-center justify-center py-10 space-y-4 text-indigo-600">
|
||||
<Loader2 className="h-8 w-8 animate-spin" />
|
||||
<p className="text-sm font-medium">Verileriniz analiz ediliyor...</p>
|
||||
<p className="text-sm font-medium">{t("finance.ai.analyzing")}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -701,10 +746,10 @@ function AIFinanceDialog() {
|
||||
|
||||
{result && (
|
||||
<DialogFooter className="gap-2 sm:gap-0">
|
||||
<Button effect="shine" variant="secondary" onClick={() => setOpen(false)}>Kapat</Button>
|
||||
<Button effect="shine" variant="secondary" onClick={() => setOpen(false)}>{t("finance.ai.close")}</Button>
|
||||
<Button effect="shine" variant="default" onClick={handleAnalyze} className="gap-2">
|
||||
<Brain className="h-4 w-4" />
|
||||
Yeniden Oluştur
|
||||
{t("finance.ai.regenerate")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
)}
|
||||
@@ -717,7 +762,7 @@ function calculateExpenseCategories(transactions: FinanceTransactionItem[]) {
|
||||
const totals = new Map<string, number>();
|
||||
for (const transaction of transactions) {
|
||||
if (transaction.type !== "expense") continue;
|
||||
const category = transaction.category || "Kategori yok";
|
||||
const category = transaction.category || "__uncategorized";
|
||||
totals.set(category, (totals.get(category) || 0) + transaction.amount);
|
||||
}
|
||||
|
||||
@@ -732,6 +777,16 @@ function calculateExpenseCategories(transactions: FinanceTransactionItem[]) {
|
||||
.slice(0, 6);
|
||||
}
|
||||
|
||||
function resolveTranslatedError(
|
||||
t: ReturnType<typeof useTranslations>,
|
||||
error: unknown,
|
||||
fallbackKey: string,
|
||||
) {
|
||||
if (!(error instanceof Error)) return t(fallbackKey);
|
||||
if (/^(finance|api|validation)\./.test(error.message)) return t(error.message);
|
||||
return error.message || t(fallbackKey);
|
||||
}
|
||||
|
||||
function formatCurrency(value: number, currency = "USD") {
|
||||
return new Intl.NumberFormat(getDocumentIntlLocale(), {
|
||||
style: "currency",
|
||||
|
||||
@@ -1,28 +1,47 @@
|
||||
import { FinanceClient, type FinanceRelationOption, type FinanceTransactionItem } from "@/app/(dashboard)/finance/finance-client";
|
||||
import { requireFreelancerBackend } from "@/server/web/freelancer";
|
||||
import { getSqliteConnection } from "@/server/db/client";
|
||||
import { ContentTranslationService, type ContentTranslationRow } from "@/server/i18n/content";
|
||||
import { resolveFreelancerLocale } from "@/server/i18n/resolver";
|
||||
import { getClientI18nPayload } from "@/server/i18n/translator";
|
||||
import { I18nProvider } from "@/components/i18n/i18n-provider";
|
||||
|
||||
export default async function FinancePage() {
|
||||
const { actor, service } = await requireFreelancerBackend();
|
||||
const { context, actor, service } = await requireFreelancerBackend();
|
||||
const locale = await resolveFreelancerLocale(context);
|
||||
const content = new ContentTranslationService(getSqliteConnection().db);
|
||||
const localization = content.getLocalizationContext(actor);
|
||||
const rows = service.listFinanceTransactions(actor);
|
||||
const clientRows = service.listClients(actor);
|
||||
const projectRows = service.listProjects(actor);
|
||||
const clients = new Map(clientRows.map((item) => [item.id, item.name]));
|
||||
const projects = new Map(projectRows.map((item) => [item.id, item.name]));
|
||||
|
||||
const transactions: FinanceTransactionItem[] = rows.map((transaction) => ({
|
||||
id: transaction.id,
|
||||
type: transaction.type,
|
||||
amount: transaction.amountMinor / 100,
|
||||
currency: transaction.currency,
|
||||
transaction_date: transaction.transactionDate,
|
||||
category: transaction.category,
|
||||
payment_status: transaction.paymentStatus,
|
||||
client_id: transaction.clientId,
|
||||
project_id: transaction.projectId,
|
||||
clientName: transaction.clientId ? clients.get(transaction.clientId) ?? null : null,
|
||||
projectName: transaction.projectId ? projects.get(transaction.projectId) ?? null : null,
|
||||
description: transaction.description,
|
||||
}));
|
||||
const transactionsTranslations = content.listBatch("finance_transaction", rows.map((transaction) => transaction.id));
|
||||
|
||||
const transactions: FinanceTransactionItem[] = rows.map((transaction) => {
|
||||
const translationRows = transactionsTranslations.get(transaction.id) ?? [];
|
||||
const resolved = content.resolveEntity("finance_transaction", transaction, {
|
||||
locale: locale.locale,
|
||||
defaultLocale: localization.defaultLocale,
|
||||
translations: translationRows,
|
||||
});
|
||||
return {
|
||||
id: transaction.id,
|
||||
type: transaction.type,
|
||||
amount: transaction.amountMinor / 100,
|
||||
currency: transaction.currency,
|
||||
transaction_date: transaction.transactionDate,
|
||||
category: resolved.category,
|
||||
payment_status: transaction.paymentStatus,
|
||||
client_id: transaction.clientId,
|
||||
project_id: transaction.projectId,
|
||||
clientName: transaction.clientId ? clients.get(transaction.clientId) ?? null : null,
|
||||
projectName: transaction.projectId ? projects.get(transaction.projectId) ?? null : null,
|
||||
description: resolved.description,
|
||||
translations: toLocalizedValues(translationRows),
|
||||
};
|
||||
});
|
||||
const clientOptions: FinanceRelationOption[] = clientRows
|
||||
.filter((item) => item.status !== "archived")
|
||||
.map(({ id, name }) => ({ id, name }));
|
||||
@@ -30,5 +49,19 @@ export default async function FinancePage() {
|
||||
.filter((item) => item.status !== "cancelled")
|
||||
.map(({ id, name, clientId }) => ({ id, name, client_id: clientId }));
|
||||
|
||||
return <FinanceClient transactions={transactions} clients={clientOptions} projects={projectOptions} />;
|
||||
const i18nPayload = await getClientI18nPayload(locale.locale, ["finance", "common"]);
|
||||
|
||||
return (
|
||||
<I18nProvider {...i18nPayload}>
|
||||
<FinanceClient transactions={transactions} clients={clientOptions} projects={projectOptions} localization={localization} />
|
||||
</I18nProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function toLocalizedValues(rows: ContentTranslationRow[]) {
|
||||
return rows.reduce<Record<string, Record<string, string>>>((result, row) => {
|
||||
result[row.locale] = result[row.locale] ?? {};
|
||||
result[row.locale][row.field] = row.value;
|
||||
return result;
|
||||
}, {});
|
||||
}
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { getSqliteConnection } from "@/server/db/client";
|
||||
import {
|
||||
ContentTranslationService,
|
||||
parseContentTranslationsFromFormData,
|
||||
} from "@/server/i18n/content";
|
||||
import { cleanText, requiredText } from "@/server/web/form-data";
|
||||
import { requireFreelancerBackend } from "@/server/web/freelancer";
|
||||
|
||||
@@ -9,31 +14,39 @@ function score(value: FormDataEntryValue | null): number | null {
|
||||
return Number.isInteger(parsed) && parsed >= 1 && parsed <= 5 ? parsed : null;
|
||||
}
|
||||
|
||||
function payload(formData: FormData) {
|
||||
function payload(formData: FormData, translations?: Record<string, Record<string, string | null>>, defaultLocale = "tr") {
|
||||
const moodScore = score(formData.get("mood_score"));
|
||||
const energyScore = score(formData.get("energy_score"));
|
||||
if (!moodScore || !energyScore) throw new Error("Mood ve enerji skorları zorunludur.");
|
||||
if (!moodScore || !energyScore) throw new Error("journal.errors.scoresRequired");
|
||||
const localized = translations?.[defaultLocale] ?? {};
|
||||
return {
|
||||
entryDate: cleanText(formData.get("log_date")) ?? new Date().toISOString().slice(0, 10),
|
||||
moodScore,
|
||||
energyScore,
|
||||
workSatisfactionScore: score(formData.get("work_satisfaction_score")),
|
||||
note: cleanText(formData.get("note")),
|
||||
moodLabel: localized.moodLabel ?? cleanText(formData.get("mood_label")),
|
||||
note: localized.note ?? cleanText(formData.get("note")),
|
||||
};
|
||||
}
|
||||
|
||||
export async function createDailyLogRecord(formData: FormData) {
|
||||
const { actor, service } = await requireFreelancerBackend();
|
||||
service.saveJournalEntry(actor, payload(formData));
|
||||
const i18n = new ContentTranslationService(getSqliteConnection().db);
|
||||
const context = i18n.getLocalizationContext(actor);
|
||||
const translations = parseContentTranslationsFromFormData(formData, "journal_entry", context);
|
||||
service.saveJournalEntry(actor, { ...payload(formData, translations, context.defaultLocale), translations });
|
||||
revalidatePath("/journal");
|
||||
}
|
||||
|
||||
export async function updateDailyLogRecord(formData: FormData) {
|
||||
const { actor, service } = await requireFreelancerBackend();
|
||||
const i18n = new ContentTranslationService(getSqliteConnection().db);
|
||||
const context = i18n.getLocalizationContext(actor);
|
||||
const translations = parseContentTranslationsFromFormData(formData, "journal_entry", context);
|
||||
service.updateJournalEntry(
|
||||
actor,
|
||||
requiredText(formData.get("id"), "Günlük kaydı bulunamadı."),
|
||||
payload(formData),
|
||||
requiredText(formData.get("id"), "journal.errors.notFound"),
|
||||
{ ...payload(formData, translations, context.defaultLocale), translations },
|
||||
);
|
||||
revalidatePath("/journal");
|
||||
}
|
||||
@@ -42,7 +55,7 @@ export async function deleteDailyLogRecord(formData: FormData) {
|
||||
const { actor, service } = await requireFreelancerBackend();
|
||||
service.deleteJournalEntry(
|
||||
actor,
|
||||
requiredText(formData.get("id"), "Silinecek günlük kaydı bulunamadı."),
|
||||
requiredText(formData.get("id"), "journal.errors.deleteNotFound"),
|
||||
);
|
||||
revalidatePath("/journal");
|
||||
}
|
||||
|
||||
@@ -2,12 +2,14 @@
|
||||
|
||||
import { getDocumentIntlLocale } from "@/lib/i18n/browser";
|
||||
import { useTranslations } from "@/components/i18n/i18n-provider";
|
||||
import { LocalizedFields, type LocalizedFieldLocale, type LocalizedFieldValues } from "@/components/i18n/localized-fields";
|
||||
import { contentTranslationRegistry } from "@/lib/i18n/content";
|
||||
import {
|
||||
createDailyLogRecord,
|
||||
deleteDailyLogRecord,
|
||||
updateDailyLogRecord,
|
||||
} from "@/app/(dashboard)/journal/actions";
|
||||
import { Badge, Button, Card, CardContent, Input, Label, Textarea } from "poyraz-ui/atoms";
|
||||
import { Badge, Button, Card, CardContent, Input, Label } from "poyraz-ui/atoms";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
@@ -46,22 +48,28 @@ export type DailyLogItem = {
|
||||
mood_score: number;
|
||||
energy_score: number;
|
||||
work_satisfaction_score: number | null;
|
||||
mood_label: string | null;
|
||||
note: string | null;
|
||||
translations?: LocalizedFieldValues;
|
||||
};
|
||||
|
||||
type JournalClientProps = {
|
||||
logs: DailyLogItem[];
|
||||
localization: {
|
||||
defaultLocale: string;
|
||||
locales: LocalizedFieldLocale[];
|
||||
};
|
||||
};
|
||||
|
||||
const scoreLabels: Record<number, string> = {
|
||||
1: "Çok düşük",
|
||||
2: "Düşük",
|
||||
3: "Orta",
|
||||
4: "İyi",
|
||||
5: "Çok iyi",
|
||||
};
|
||||
const scoreLabels = (t: ReturnType<typeof useTranslations>) => ({
|
||||
1: t("journal.scores.veryLow"),
|
||||
2: t("journal.scores.low"),
|
||||
3: t("journal.scores.medium"),
|
||||
4: t("journal.scores.high"),
|
||||
5: t("journal.scores.veryHigh"),
|
||||
});
|
||||
|
||||
export function JournalClient({ logs }: JournalClientProps) {
|
||||
export function JournalClient({ logs, localization }: JournalClientProps) {
|
||||
const t = useTranslations();
|
||||
const summary = useMemo(() => calculateSummary(logs), [logs]);
|
||||
const chartData = useMemo(
|
||||
@@ -87,31 +95,31 @@ export function JournalClient({ logs }: JournalClientProps) {
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-2 sm:flex-row">
|
||||
<DailyLogDialog mode="create" />
|
||||
<DailyLogDialog mode="create" localization={localization} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-3 md:grid-cols-4">
|
||||
<StatCard
|
||||
label="Ortalama mood"
|
||||
label={t("journal.stats.averageMood")}
|
||||
value={summary.moodAverage ? summary.moodAverage.toFixed(1) : "-"}
|
||||
icon={Smile}
|
||||
tone="primary"
|
||||
/>
|
||||
<StatCard
|
||||
label="Ortalama enerji"
|
||||
label={t("journal.stats.averageEnergy")}
|
||||
value={summary.energyAverage ? summary.energyAverage.toFixed(1) : "-"}
|
||||
icon={Battery}
|
||||
tone="green"
|
||||
/>
|
||||
<StatCard
|
||||
label="Memnuniyet"
|
||||
label={t("journal.stats.satisfaction")}
|
||||
value={summary.satisfactionAverage ? summary.satisfactionAverage.toFixed(1) : "-"}
|
||||
icon={LineChartIcon}
|
||||
tone="blue"
|
||||
/>
|
||||
<StatCard
|
||||
label="Kayıtlı gün"
|
||||
label={t("journal.stats.recordedDays")}
|
||||
value={String(logs.length)}
|
||||
icon={CalendarDays}
|
||||
tone="amber"
|
||||
@@ -122,9 +130,9 @@ export function JournalClient({ logs }: JournalClientProps) {
|
||||
<Card>
|
||||
<CardContent className="space-y-4 p-4">
|
||||
<div>
|
||||
<h2 className="text-base font-semibold text-foreground">Genel trend</h2>
|
||||
<h2 className="text-base font-semibold text-foreground">{t("journal.charts.trend.title")}</h2>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Mood, enerji ve çalışma memnuniyetinin günlük değişimi.
|
||||
{t("journal.charts.trend.description")}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -142,12 +150,12 @@ export function JournalClient({ logs }: JournalClientProps) {
|
||||
boxShadow: "0 10px 30px rgba(15, 23, 42, 0.08)",
|
||||
}}
|
||||
/>
|
||||
<Line type="monotone" dataKey="mood" name="Mood" stroke="#dc2626" strokeWidth={3} dot={{ r: 3 }} />
|
||||
<Line type="monotone" dataKey="energy" name="Enerji" stroke="#059669" strokeWidth={3} dot={{ r: 3 }} />
|
||||
<Line type="monotone" dataKey="mood" name={t("journal.fields.mood")} stroke="#dc2626" strokeWidth={3} dot={{ r: 3 }} />
|
||||
<Line type="monotone" dataKey="energy" name={t("journal.fields.energy")} stroke="#059669" strokeWidth={3} dot={{ r: 3 }} />
|
||||
<Line
|
||||
type="monotone"
|
||||
dataKey="satisfaction"
|
||||
name="Memnuniyet"
|
||||
name={t("journal.fields.satisfaction")}
|
||||
stroke="#2563eb"
|
||||
strokeWidth={3}
|
||||
dot={{ r: 3 }}
|
||||
@@ -165,15 +173,31 @@ export function JournalClient({ logs }: JournalClientProps) {
|
||||
<Card>
|
||||
<CardContent className="space-y-4 p-4">
|
||||
<div>
|
||||
<h2 className="text-base font-semibold text-foreground">Kapasite sinyali</h2>
|
||||
<p className="text-sm text-muted-foreground">Kayıtlardan kısa okuma.</p>
|
||||
<h2 className="text-base font-semibold text-foreground">{t("journal.charts.insights.title")}</h2>
|
||||
<p className="text-sm text-muted-foreground">{t("journal.charts.insights.description")}</p>
|
||||
</div>
|
||||
<div className="space-y-3 text-sm text-muted-foreground">
|
||||
{summary.insights.map((insight) => (
|
||||
<div key={insight} className="rounded-sm border border-border bg-muted/20 p-3">
|
||||
{insight}
|
||||
{summary.length === 0 ? (
|
||||
<div className="rounded-sm border border-border bg-muted/20 p-3">
|
||||
{t("journal.insights.noTrend")}
|
||||
</div>
|
||||
))}
|
||||
) : (
|
||||
<>
|
||||
<div className="rounded-sm border border-border bg-muted/20 p-3">
|
||||
{t("journal.insights.totalDays", { count: summary.length })}
|
||||
</div>
|
||||
<div className="rounded-sm border border-border bg-muted/20 p-3">
|
||||
{summary.energyAverage && summary.energyAverage < 3
|
||||
? t("journal.insights.lowEnergy")
|
||||
: t("journal.insights.balancedEnergy")}
|
||||
</div>
|
||||
<div className="rounded-sm border border-border bg-muted/20 p-3">
|
||||
{summary.moodAverage && summary.moodAverage >= 4
|
||||
? t("journal.insights.strongMood")
|
||||
: t("journal.insights.watchMood")}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
@@ -183,8 +207,8 @@ export function JournalClient({ logs }: JournalClientProps) {
|
||||
<CardContent className="space-y-4 p-4">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div>
|
||||
<h2 className="text-base font-semibold text-foreground">Günlük kayıtlar</h2>
|
||||
<p className="text-sm text-muted-foreground">{logs.length} kayıt görüntüleniyor.</p>
|
||||
<h2 className="text-base font-semibold text-foreground">{t("journal.list.title")}</h2>
|
||||
<p className="text-sm text-muted-foreground">{t("journal.list.description", { count: logs.length })}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -192,15 +216,15 @@ export function JournalClient({ logs }: JournalClientProps) {
|
||||
<div className="overflow-x-auto rounded-sm border border-border">
|
||||
<div className="min-w-[800px]">
|
||||
<div className="grid grid-cols-[0.7fr_0.7fr_0.7fr_1.8fr_0.8fr] gap-4 border-b border-border bg-muted/40 px-4 py-3 text-xs font-medium uppercase text-muted-foreground">
|
||||
<span>Tarih</span>
|
||||
<span>Mood</span>
|
||||
<span>Enerji</span>
|
||||
<span>Not</span>
|
||||
<span className="text-right">İşlem</span>
|
||||
<span>{t("journal.list.headers.date")}</span>
|
||||
<span>{t("journal.list.headers.mood")}</span>
|
||||
<span>{t("journal.list.headers.energy")}</span>
|
||||
<span>{t("journal.list.headers.note")}</span>
|
||||
<span className="text-right">{t("journal.list.headers.action")}</span>
|
||||
</div>
|
||||
<div className="divide-y divide-border">
|
||||
{logs.map((log) => (
|
||||
<DailyLogRow key={log.id} log={log} />
|
||||
<DailyLogRow key={log.id} log={log} localization={localization} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
@@ -214,28 +238,34 @@ export function JournalClient({ logs }: JournalClientProps) {
|
||||
);
|
||||
}
|
||||
|
||||
function DailyLogRow({ log }: { log: DailyLogItem }) {
|
||||
function DailyLogRow({ log, localization }: { log: DailyLogItem; localization: JournalClientProps["localization"] }) {
|
||||
const t = useTranslations();
|
||||
return (
|
||||
<div className="grid gap-4 px-4 py-4 grid-cols-[0.7fr_0.7fr_0.7fr_1.8fr_0.8fr] items-center">
|
||||
<div>
|
||||
<div className="font-medium text-foreground">{formatDate(log.log_date)}</div>
|
||||
<div className="text-xs text-muted-foreground">{formatWeekday(log.log_date)}</div>
|
||||
</div>
|
||||
<ScoreBadge score={log.mood_score} tone="primary" />
|
||||
<div className="min-w-0">
|
||||
<ScoreBadge score={log.mood_score} tone="primary" />
|
||||
{log.mood_label ? (
|
||||
<p className="mt-1 truncate text-xs text-muted-foreground">{log.mood_label}</p>
|
||||
) : null}
|
||||
</div>
|
||||
<ScoreBadge score={log.energy_score} tone="green" />
|
||||
<div className="min-w-0 text-sm text-muted-foreground">
|
||||
<p className="line-clamp-2">{log.note || "Not eklenmedi."}</p>
|
||||
<p className="line-clamp-2">{log.note || t("journal.empty.noNote")}</p>
|
||||
{log.work_satisfaction_score ? (
|
||||
<p className="mt-1 text-xs">Çalışma memnuniyeti: {log.work_satisfaction_score}/5</p>
|
||||
<p className="mt-1 text-xs">{t("journal.fields.satisfaction")}: {log.work_satisfaction_score}/5</p>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="flex justify-start gap-2 lg:justify-end">
|
||||
<DailyLogDialog mode="edit" log={log} />
|
||||
<DailyLogDialog mode="edit" log={log} localization={localization} />
|
||||
<form action={deleteDailyLogRecord}>
|
||||
<input type="hidden" name="id" value={log.id} />
|
||||
<Button effect="shine" type="submit" variant="secondary" className="gap-2 text-rose-600">
|
||||
<Trash2 className="h-4 w-4" />
|
||||
Sil
|
||||
{t("journal.actions.delete")}
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
@@ -243,7 +273,8 @@ function DailyLogRow({ log }: { log: DailyLogItem }) {
|
||||
);
|
||||
}
|
||||
|
||||
function DailyLogDialog({ mode, log }: { mode: "create" | "edit"; log?: DailyLogItem }) {
|
||||
function DailyLogDialog({ mode, log, localization }: { mode: "create" | "edit"; log?: DailyLogItem; localization: JournalClientProps["localization"] }) {
|
||||
const t = useTranslations();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const action = mode === "create" ? createDailyLogRecord : updateDailyLogRecord;
|
||||
@@ -254,13 +285,9 @@ function DailyLogDialog({ mode, log }: { mode: "create" | "edit"; log?: DailyLog
|
||||
try {
|
||||
await action(formData);
|
||||
setOpen(false);
|
||||
toast.success(mode === "create" ? "Günlük eklendi." : "Günlük güncellendi.");
|
||||
toast.success(mode === "create" ? t("journal.form.messages.createSuccess") : t("journal.form.messages.updateSuccess"));
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Günlük kaydedilirken beklenmeyen bir hata oluştu.",
|
||||
);
|
||||
toast.error(resolveTranslatedError(t, error, "journal.form.messages.error"));
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
@@ -271,26 +298,26 @@ function DailyLogDialog({ mode, log }: { mode: "create" | "edit"; log?: DailyLog
|
||||
<DialogTrigger asChild>
|
||||
<Button effect="shine" variant={mode === "create" ? "default" : "secondary"} className="gap-2">
|
||||
{mode === "create" ? <Plus className="h-4 w-4" /> : <Pencil className="h-4 w-4" />}
|
||||
{mode === "create" ? "Günlük ekle" : "Düzenle"}
|
||||
{mode === "create" ? t("journal.actions.add") : t("journal.actions.edit")}
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="flex max-h-[calc(100dvh-2rem)] w-[calc(100vw-2rem)] flex-col overflow-hidden p-0 sm:max-h-[min(680px,calc(100dvh-4rem))] sm:max-w-xl data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95">
|
||||
<form action={handleSubmit} className="flex min-h-0 flex-1 flex-col overflow-hidden">
|
||||
{log ? <input type="hidden" name="id" value={log.id} /> : null}
|
||||
<DialogHeader className="shrink-0 px-5 pb-4 pt-5 pr-12">
|
||||
<DialogTitle>{mode === "create" ? "Yeni günlük kayıt" : "Günlük kaydı düzenle"}</DialogTitle>
|
||||
<DialogTitle>{mode === "create" ? t("journal.form.createTitle") : t("journal.form.editTitle")}</DialogTitle>
|
||||
<DialogDescription>
|
||||
Günün mood, enerji ve çalışma memnuniyeti skorlarını kaydet.
|
||||
{t("journal.form.description")}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="tiny-scrollbar min-h-0 flex-1 overflow-y-auto px-5 pb-5">
|
||||
<DailyLogFormFields log={log} />
|
||||
<DailyLogFormFields log={log} localization={localization} />
|
||||
</div>
|
||||
|
||||
<DialogFooter className="shrink-0 border-t border-border bg-background p-5">
|
||||
<Button variant="default" effect="shine" type="submit" disabled={isSubmitting} className="w-full gap-2 sm:w-auto">
|
||||
{isSubmitting ? "Kaydediliyor" : mode === "create" ? "Kaydı ekle" : "Değişiklikleri kaydet"}
|
||||
{isSubmitting ? t("journal.actions.saving") : mode === "create" ? t("journal.form.submitCreate") : t("journal.form.submitEdit")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
@@ -299,7 +326,8 @@ function DailyLogDialog({ mode, log }: { mode: "create" | "edit"; log?: DailyLog
|
||||
);
|
||||
}
|
||||
|
||||
function DailyLogFormFields({ log }: { log?: DailyLogItem }) {
|
||||
function DailyLogFormFields({ log, localization }: { log?: DailyLogItem; localization: JournalClientProps["localization"] }) {
|
||||
const t = useTranslations();
|
||||
const [moodScore, setMoodScore] = useState(log?.mood_score || 3);
|
||||
const [energyScore, setEnergyScore] = useState(log?.energy_score || 3);
|
||||
const [satisfactionScore, setSatisfactionScore] = useState(log?.work_satisfaction_score || 3);
|
||||
@@ -307,7 +335,7 @@ function DailyLogFormFields({ log }: { log?: DailyLogItem }) {
|
||||
return (
|
||||
<div className="grid gap-5">
|
||||
<div className="grid gap-2">
|
||||
<Label>Tarih</Label>
|
||||
<Label>{t("journal.fields.date")}</Label>
|
||||
<Input
|
||||
name="log_date"
|
||||
type="date"
|
||||
@@ -317,32 +345,41 @@ function DailyLogFormFields({ log }: { log?: DailyLogItem }) {
|
||||
|
||||
<ScorePicker
|
||||
name="mood_score"
|
||||
label="Mood skoru"
|
||||
label={t("journal.fields.mood")}
|
||||
value={moodScore}
|
||||
onChange={setMoodScore}
|
||||
/>
|
||||
<ScorePicker
|
||||
name="energy_score"
|
||||
label="Enerji skoru"
|
||||
label={t("journal.fields.energy")}
|
||||
value={energyScore}
|
||||
onChange={setEnergyScore}
|
||||
/>
|
||||
<ScorePicker
|
||||
name="work_satisfaction_score"
|
||||
label="Çalışma memnuniyeti"
|
||||
label={t("journal.fields.satisfaction")}
|
||||
value={satisfactionScore}
|
||||
onChange={setSatisfactionScore}
|
||||
/>
|
||||
|
||||
<div className="grid gap-2">
|
||||
<Label>Not</Label>
|
||||
<Textarea
|
||||
name="note"
|
||||
defaultValue={log?.note || ""}
|
||||
rows={4}
|
||||
placeholder="Bugün nasıl geçti, enerjini etkileyen şeyler nelerdi?"
|
||||
/>
|
||||
</div>
|
||||
<LocalizedFields
|
||||
idPrefix={`journal-${log?.id || "new"}-content`}
|
||||
defaultLocale={localization.defaultLocale}
|
||||
locales={localization.locales}
|
||||
fields={contentTranslationRegistry.journal_entry
|
||||
.map((f) => ({
|
||||
...f,
|
||||
label: t(`journal.fields.${f.name}`) || f.label,
|
||||
placeholder: "placeholder" in f && typeof f.placeholder === "string"
|
||||
? t(`journal.placeholders.${f.name}`) || f.placeholder
|
||||
: undefined,
|
||||
}))}
|
||||
values={log?.translations}
|
||||
fallbackValues={{
|
||||
moodLabel: log?.mood_label,
|
||||
note: log?.note,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -358,11 +395,14 @@ function ScorePicker({
|
||||
value: number;
|
||||
onChange: (value: number) => void;
|
||||
}) {
|
||||
const t = useTranslations();
|
||||
const labels = scoreLabels(t);
|
||||
|
||||
return (
|
||||
<div className="grid gap-2">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<Label>{label}</Label>
|
||||
<span className="text-sm text-muted-foreground">{scoreLabels[value]}</span>
|
||||
<span className="text-sm text-muted-foreground">{labels[value as keyof typeof labels]}</span>
|
||||
</div>
|
||||
<input type="hidden" name={name} value={value} />
|
||||
<div className="grid grid-cols-5 gap-2">
|
||||
@@ -383,21 +423,34 @@ function ScorePicker({
|
||||
}
|
||||
|
||||
function ScoreBadge({ score, tone }: { score: number; tone: "primary" | "green" }) {
|
||||
const t = useTranslations();
|
||||
const labels = scoreLabels(t);
|
||||
const className =
|
||||
tone === "green"
|
||||
? "border-emerald-200 bg-emerald-50 text-emerald-700"
|
||||
: "border-primary/20 bg-primary/10 text-primary";
|
||||
|
||||
return <Badge className={className}>{score}/5 · {scoreLabels[score]}</Badge>;
|
||||
return <Badge className={className}>{score}/5 · {labels[score as keyof typeof labels]}</Badge>;
|
||||
}
|
||||
|
||||
function resolveTranslatedError(
|
||||
t: ReturnType<typeof useTranslations>,
|
||||
error: unknown,
|
||||
fallbackKey: string,
|
||||
) {
|
||||
if (!(error instanceof Error)) return t(fallbackKey);
|
||||
if (/^(journal|api|validation)\./.test(error.message)) return t(error.message);
|
||||
return error.message || t(fallbackKey);
|
||||
}
|
||||
|
||||
function EmptyState() {
|
||||
const t = useTranslations();
|
||||
return (
|
||||
<div className="flex min-h-72 flex-col items-center justify-center rounded-sm border border-dashed border-border bg-muted/20 p-8 text-center">
|
||||
<Activity className="h-10 w-10 text-muted-foreground" />
|
||||
<h3 className="mt-4 text-lg font-semibold text-foreground">Henüz günlük kayıt yok</h3>
|
||||
<h3 className="mt-4 text-lg font-semibold text-foreground">{t("journal.empty.noRecordTitle")}</h3>
|
||||
<p className="mt-2 max-w-md text-sm text-muted-foreground">
|
||||
Mood ve enerji trendini görmek için ilk günlük kaydını ekle.
|
||||
{t("journal.empty.noRecordDesc")}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
@@ -412,25 +465,7 @@ function calculateSummary(logs: DailyLogItem[]) {
|
||||
.filter((score): score is number => typeof score === "number"),
|
||||
);
|
||||
|
||||
const insights = [];
|
||||
|
||||
if (logs.length === 0) {
|
||||
insights.push("Henüz okunabilir bir trend yok.");
|
||||
} else {
|
||||
insights.push(`Toplam ${logs.length} günlük kayıt var.`);
|
||||
insights.push(
|
||||
energyAverage && energyAverage < 3
|
||||
? "Enerji ortalaması düşük. Dashboard raporlarında geciken işler ile birlikte okunmalı."
|
||||
: "Enerji ortalaması dengeli görünüyor.",
|
||||
);
|
||||
insights.push(
|
||||
moodAverage && moodAverage >= 4
|
||||
? "Mood seviyesi güçlü. Yüksek odak isteyen işler için iyi bir dönem olabilir."
|
||||
: "Mood trendi izlenmeli. Not alanı hangi günlerin zor geçtiğini anlamak için önemli.",
|
||||
);
|
||||
}
|
||||
|
||||
return { moodAverage, energyAverage, satisfactionAverage, insights };
|
||||
return { moodAverage, energyAverage, satisfactionAverage, length: logs.length };
|
||||
}
|
||||
|
||||
function average(values: number[]) {
|
||||
|
||||
@@ -1,22 +1,56 @@
|
||||
import { JournalClient, type DailyLogItem } from "@/app/(dashboard)/journal/journal-client";
|
||||
import { requireFreelancerBackend } from "@/server/web/freelancer";
|
||||
import { getSqliteConnection } from "@/server/db/client";
|
||||
import { ContentTranslationService, type ContentTranslationRow } from "@/server/i18n/content";
|
||||
import { resolveFreelancerLocale } from "@/server/i18n/resolver";
|
||||
import { getClientI18nPayload } from "@/server/i18n/translator";
|
||||
import { I18nProvider } from "@/components/i18n/i18n-provider";
|
||||
|
||||
export default async function JournalPage() {
|
||||
const { actor, service } = await requireFreelancerBackend();
|
||||
const logs: DailyLogItem[] = service.listJournalEntries(actor)
|
||||
.slice(0, 180)
|
||||
.flatMap((entry) =>
|
||||
entry.moodScore == null || entry.energyScore == null
|
||||
? []
|
||||
: [{
|
||||
id: entry.id,
|
||||
log_date: entry.entryDate,
|
||||
mood_score: entry.moodScore,
|
||||
energy_score: entry.energyScore,
|
||||
work_satisfaction_score: entry.workSatisfactionScore,
|
||||
note: entry.note,
|
||||
}],
|
||||
);
|
||||
const { context, actor, service } = await requireFreelancerBackend();
|
||||
const locale = await resolveFreelancerLocale(context);
|
||||
const content = new ContentTranslationService(getSqliteConnection().db);
|
||||
const localization = content.getLocalizationContext(actor);
|
||||
|
||||
return <JournalClient logs={logs} />;
|
||||
const rawLogs = service.listJournalEntries(actor).slice(0, 180);
|
||||
const logsTranslations = content.listBatch("journal_entry", rawLogs.map((log) => log.id));
|
||||
|
||||
const logs: DailyLogItem[] = rawLogs
|
||||
.flatMap((entry) => {
|
||||
if (entry.moodScore == null || entry.energyScore == null) return [];
|
||||
|
||||
const translationRows = logsTranslations.get(entry.id) ?? [];
|
||||
const resolved = content.resolveEntity("journal_entry", entry, {
|
||||
locale: locale.locale,
|
||||
defaultLocale: localization.defaultLocale,
|
||||
translations: translationRows,
|
||||
});
|
||||
|
||||
return [{
|
||||
id: entry.id,
|
||||
log_date: entry.entryDate,
|
||||
mood_score: entry.moodScore,
|
||||
energy_score: entry.energyScore,
|
||||
work_satisfaction_score: entry.workSatisfactionScore,
|
||||
mood_label: resolved.moodLabel,
|
||||
note: resolved.note,
|
||||
translations: toLocalizedValues(translationRows),
|
||||
}];
|
||||
});
|
||||
|
||||
const i18nPayload = await getClientI18nPayload(locale.locale, ["journal", "common"]);
|
||||
|
||||
return (
|
||||
<I18nProvider {...i18nPayload}>
|
||||
<JournalClient logs={logs} localization={localization} />
|
||||
</I18nProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function toLocalizedValues(rows: ContentTranslationRow[]) {
|
||||
return rows.reduce<Record<string, Record<string, string>>>((result, row) => {
|
||||
result[row.locale] = result[row.locale] ?? {};
|
||||
result[row.locale][row.field] = row.value;
|
||||
return result;
|
||||
}, {});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user