feat(dashboard): Next.js 16 merchant panel with offline POS and PWA

Complete merchant dashboard upgrade:

Next.js 16 compatibility:
- Fix params/searchParams typed as Promise<{}> throughout App Router
- Replace middleware.ts with proxy.ts (Next.js 16 convention)
- Remove unused @ts-expect-error directives caught by stricter TS
- Cast dynamic next-intl t() keys to fix TranslateArgs type errors

Offline POS:
- IndexedDB queue (meezi_pos_offline) for orders created while offline
- Zustand sync store tracking queueCount, isSyncing, isOnline
- useOfflineSync hook: auto-syncs on reconnect/visibility-change
- SyncStatusIndicator chip in topbar (amber=offline, blue=syncing)
- submitOrderToApi falls back to local order on network failure
- Local orders skip payment flow; sync on reconnect

PWA (installable):
- @ducanh2912/next-pwa with Workbox runtime caching rules
- Web App Manifest (manifest.ts) — RTL/Farsi, theme #0F6E56
- PWA icons: 192px, 512px, maskable 512px
- next.config.ts replaces next.config.mjs

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
soroush.asadi
2026-05-27 21:34:12 +03:30
parent ef15fd6247
commit 131ecdbbe6
208 changed files with 37123 additions and 0 deletions
@@ -0,0 +1,228 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { useSearchParams } from "next/navigation";
import { useQuery, useMutation } from "@tanstack/react-query";
import { useTranslations } from "next-intl";
import { apiGet, apiPost } from "@/lib/api/client";
import { isCafeOwner } from "@/lib/auth-permissions";
import { useAuthStore } from "@/lib/stores/auth.store";
import { formatNumber } from "@/lib/format";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { PageHeader } from "@/components/layout/page-header";
import { PlanComparison } from "@/components/settings/plan-comparison";
import type { AuthTokenResponse } from "@/lib/api/types";
import { Alert } from "@/components/ui/alert";
import { notify } from "@/lib/notify";
type BillingStatus = {
planTier: string;
planExpiresAt: string | null;
ordersToday: number;
ordersDailyLimit: number | null;
customersCount: number;
customersLimit: number | null;
smsUsedThisMonth: number;
smsMonthlyLimit: number;
menu3dEnabled: boolean;
discoverProfileEnabled: boolean;
isPlanExpired: boolean;
};
type SubscribeResponse = {
paymentId: string;
paymentUrl: string;
};
type PaymentMethod = {
id: string;
displayNameFa: string;
isDefault: boolean;
};
export function SubscriptionScreen() {
const t = useTranslations("subscription");
const tSettings = useTranslations("settings");
const searchParams = useSearchParams();
const cafeId = useAuthStore((s) => s.user?.cafeId);
const role = useAuthStore((s) => s.user?.role);
const setAuth = useAuthStore((s) => s.setAuth);
const billingRefreshed = useRef(false);
const [billingBanner, setBillingBanner] = useState<"success" | "failed" | null>(null);
const [paymentMethod, setPaymentMethod] = useState("");
useEffect(() => {
const billing = searchParams.get("billing");
if (billing === "success") {
notify.success(t("paymentSuccess"));
setBillingBanner("success");
}
if (billing === "failed") {
notify.error(t("paymentFailed"));
setBillingBanner("failed");
}
}, [searchParams, t]);
const { data: status, isLoading, refetch } = useQuery({
queryKey: ["billing-status", cafeId],
queryFn: () => apiGet<BillingStatus>("/api/billing/status"),
enabled: !!cafeId,
});
const { data: paymentMethods = [] } = useQuery({
queryKey: ["billing-payment-methods", cafeId],
queryFn: () => apiGet<PaymentMethod[]>("/api/billing/payment-methods"),
enabled: !!cafeId && isCafeOwner(role),
});
useEffect(() => {
if (!paymentMethod && paymentMethods.length > 0) {
const def = paymentMethods.find((m) => m.isDefault) ?? paymentMethods[0];
setPaymentMethod(def.id);
}
}, [paymentMethods, paymentMethod]);
useEffect(() => {
if (searchParams.get("billing") !== "success" || billingRefreshed.current) return;
const refresh = localStorage.getItem("meezi_refresh_token");
if (!refresh) return;
billingRefreshed.current = true;
apiPost<AuthTokenResponse>("/api/auth/refresh", { refreshToken: refresh })
.then((tokens) => {
setAuth(tokens);
refetch();
})
.catch(() => notify.warning(tSettings("profile.reloginHint")));
}, [searchParams, setAuth, refetch, tSettings]);
const subscribe = useMutation({
mutationFn: (body: { planTier: string; months: number; paymentMethod: string }) =>
apiPost<SubscribeResponse>("/api/billing/subscribe", body),
onSuccess: (data) => {
window.location.href = data.paymentUrl;
},
});
if (!cafeId) return null;
if (!isCafeOwner(role)) {
return (
<div className="space-y-6">
<PageHeader title={t("title")} subtitle={t("subtitle")} />
<p className="text-sm text-muted-foreground">{t("ownerOnly")}</p>
</div>
);
}
const expiry = status?.planExpiresAt
? new Date(status.planExpiresAt).toLocaleDateString("fa-IR")
: t("noExpiry");
return (
<div className="space-y-6">
<PageHeader title={t("title")} subtitle={t("subtitle")} />
{billingBanner ? (
<Alert
variant={billingBanner === "failed" ? "destructive" : "success"}
onDismiss={() => setBillingBanner(null)}
>
{billingBanner === "failed" ? t("paymentFailed") : t("paymentSuccess")}
</Alert>
) : null}
<Card className="rounded-xl border border-border/80 shadow-sm">
<CardHeader>
<CardTitle className="text-base">{t("currentPlan")}</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
{isLoading ? (
<p className="text-sm text-muted-foreground">{t("loading")}</p>
) : status ? (
<>
<div className="flex flex-wrap items-center gap-2">
<Badge>{status.planTier}</Badge>
{status.isPlanExpired ? (
<Badge className="bg-[#A32D2D] text-white hover:bg-[#A32D2D]">
{t("planExpired")}
</Badge>
) : null}
<span className="text-sm text-muted-foreground">
{t("expires")}: {expiry}
</span>
<Button size="sm" variant="ghost" onClick={() => refetch()}>
{t("refresh")}
</Button>
</div>
<ul className="space-y-1 text-sm text-muted-foreground">
<li>
{t("ordersToday")}: {formatNumber(status.ordersToday)}
{status.ordersDailyLimit != null &&
` / ${formatNumber(status.ordersDailyLimit)}`}
</li>
<li>
{t("customers")}: {formatNumber(status.customersCount)}
{status.customersLimit != null &&
` / ${formatNumber(status.customersLimit)}`}
</li>
<li>
{t("smsUsage")}: {formatNumber(status.smsUsedThisMonth)}
{status.smsMonthlyLimit >= 0 &&
` / ${formatNumber(status.smsMonthlyLimit)}`}
</li>
<li>
{t("featureMenu3d")}:{" "}
{status.menu3dEnabled ? t("featureOn") : t("featureOff")}
</li>
<li>
{t("featureDiscover")}:{" "}
{status.discoverProfileEnabled ? t("featureOn") : t("featureOff")}
</li>
</ul>
</>
) : null}
</CardContent>
</Card>
{paymentMethods.length > 0 ? (
<Card className="rounded-xl border border-border/80 shadow-sm">
<CardHeader className="pb-2">
<CardTitle className="text-base">{t("paymentMethod")}</CardTitle>
</CardHeader>
<CardContent className="flex flex-wrap gap-2">
{paymentMethods.map((m) => (
<button
key={m.id}
type="button"
onClick={() => setPaymentMethod(m.id)}
className={cn(
"rounded-lg border px-3 py-2 text-sm transition active:scale-[0.98]",
paymentMethod === m.id
? "border-[#0F6E56] bg-[#E1F5EE] text-[#0F6E56]"
: "border-border/80 hover:border-[#0F6E56]/40"
)}
>
{m.displayNameFa}
</button>
))}
</CardContent>
</Card>
) : null}
<PlanComparison
currentPlan={status?.planTier ?? "Free"}
onSubscribe={(planTier) =>
subscribe.mutate({
planTier,
months: 1,
paymentMethod: paymentMethod || paymentMethods[0]?.id || "zarinpal",
})
}
isSubscribing={subscribe.isPending}
/>
</div>
);
}