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
+111
View File
@@ -0,0 +1,111 @@
/**
* IndexedDB wrapper for the POS offline order queue.
* All reads/writes happen in a single "order_queue" object store.
*/
export type OfflineQueueItem = {
/** Local UUID primary key */
id: string;
/** "create_order" or "add_items_to_order" */
type: "create_order" | "add_items";
cafeId: string;
/**
* For add_items: the real server order ID.
* For create_order: null (no server ID yet).
*/
targetOrderId: string | null;
/** Raw body to POST/PUT */
payload: unknown;
createdAt: string;
retries: number;
status: "pending" | "failed";
};
const DB_NAME = "meezi_pos_offline";
const DB_VERSION = 1;
const STORE = "order_queue";
let _db: IDBDatabase | null = null;
function openDb(): Promise<IDBDatabase> {
if (_db) return Promise.resolve(_db);
return new Promise((resolve, reject) => {
const req = indexedDB.open(DB_NAME, DB_VERSION);
req.onupgradeneeded = (e) => {
const db = (e.target as IDBOpenDBRequest).result;
if (!db.objectStoreNames.contains(STORE)) {
db.createObjectStore(STORE, { keyPath: "id" });
}
};
req.onsuccess = () => {
_db = req.result;
resolve(_db);
};
req.onerror = () => reject(req.error);
});
}
export async function enqueueOfflineItem(
item: Omit<OfflineQueueItem, "retries" | "status">
): Promise<void> {
const db = await openDb();
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE, "readwrite");
tx.objectStore(STORE).put({ ...item, retries: 0, status: "pending" });
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
});
}
export async function getQueueCount(): Promise<number> {
try {
const db = await openDb();
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE, "readonly");
const req = tx.objectStore(STORE).count();
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
} catch {
return 0;
}
}
export async function getAllQueueItems(): Promise<OfflineQueueItem[]> {
try {
const db = await openDb();
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE, "readonly");
const req = tx.objectStore(STORE).getAll();
req.onsuccess = () => resolve(req.result as OfflineQueueItem[]);
req.onerror = () => reject(req.error);
});
} catch {
return [];
}
}
export async function removeQueueItem(id: string): Promise<void> {
const db = await openDb();
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE, "readwrite");
tx.objectStore(STORE).delete(id);
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
});
}
export async function markQueueItemFailed(id: string): Promise<void> {
const db = await openDb();
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE, "readwrite");
const store = tx.objectStore(STORE);
const getReq = store.get(id);
getReq.onsuccess = () => {
const item = getReq.result as OfflineQueueItem;
if (item) store.put({ ...item, status: "failed", retries: item.retries + 1 });
};
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
});
}
@@ -0,0 +1,111 @@
"use client";
import { useCallback, useEffect, useRef } from "react";
import { useSyncQueueStore } from "@/lib/stores/sync-queue.store";
import {
getAllQueueItems,
getQueueCount,
removeQueueItem,
markQueueItemFailed,
} from "@/lib/offline/offline-db";
import { apiPost } from "@/lib/api/client";
/**
* Processes one queued item and returns whether it succeeded.
*/
async function processItem(item: Awaited<ReturnType<typeof getAllQueueItems>>[number]): Promise<boolean> {
try {
if (item.type === "create_order") {
const { cafeId, body } = item.payload as { cafeId: string; body: unknown };
await apiPost(`/api/cafes/${cafeId}/orders`, body as Record<string, unknown>);
} else if (item.type === "add_items") {
const { cafeId, orderId, body } = item.payload as {
cafeId: string;
orderId: string;
body: unknown;
};
await apiPost(
`/api/cafes/${cafeId}/orders/${orderId}/items`,
body as Record<string, unknown>
);
}
return true;
} catch {
return false;
}
}
/**
* Call this hook once in the app shell to:
* - Load initial queue count from IndexedDB on mount
* - Listen to online/offline events
* - Auto-sync when back online or tab becomes visible
*/
export function useOfflineSync() {
const { setQueueCount, setSyncing, setOnline } = useSyncQueueStore();
const syncLock = useRef(false);
const refreshCount = useCallback(async () => {
const n = await getQueueCount();
setQueueCount(n);
return n;
}, [setQueueCount]);
const syncQueue = useCallback(async () => {
if (syncLock.current) return;
if (!navigator.onLine) return;
const count = await refreshCount();
if (count === 0) return;
syncLock.current = true;
setSyncing(true);
try {
const items = await getAllQueueItems();
for (const item of items) {
if (item.status === "failed" && item.retries >= 3) continue; // give up after 3
const ok = await processItem(item);
if (ok) {
await removeQueueItem(item.id);
} else {
await markQueueItemFailed(item.id);
}
}
} finally {
syncLock.current = false;
setSyncing(false);
await refreshCount();
}
}, [refreshCount, setSyncing]);
useEffect(() => {
// Load initial count
void refreshCount();
// Track online state
const handleOnline = () => {
setOnline(true);
void syncQueue();
};
const handleOffline = () => setOnline(false);
setOnline(typeof navigator !== "undefined" ? navigator.onLine : true);
window.addEventListener("online", handleOnline);
window.addEventListener("offline", handleOffline);
// Sync when tab regains focus
const handleVisibility = () => {
if (document.visibilityState === "visible" && navigator.onLine) {
void syncQueue();
}
};
document.addEventListener("visibilitychange", handleVisibility);
return () => {
window.removeEventListener("online", handleOnline);
window.removeEventListener("offline", handleOffline);
document.removeEventListener("visibilitychange", handleVisibility);
};
}, [syncQueue, setOnline, refreshCount]);
return { syncQueue, refreshCount };
}