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);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user