diff --git a/.env.example b/.env.example index c682511..f9a62b3 100644 --- a/.env.example +++ b/.env.example @@ -35,6 +35,10 @@ DISCORD_BOT_TOKEN=replace-with-discord-bot-token DISCORD_CHANNEL_ID=replace-with-private-channel-id DISCORD_LOG_CHANNEL_ID=1547193755772125184 COMMISSION_DISCORD_WEBHOOK_URL=replace-with-commission-discord-webhook-url +# Generate a stable pair with: bunx web-push generate-vapid-keys --json +WEB_PUSH_PUBLIC_KEY=replace-with-vapid-public-key +WEB_PUSH_PRIVATE_KEY=replace-with-vapid-private-key +WEB_PUSH_SUBJECT=mailto:admin@example.com # S3-compatible media storage; guide and commission uploads use public CDN objects. S3_ENDPOINT=https://s3.example.internal diff --git a/README.md b/README.md index d30b39b..45ae870 100644 --- a/README.md +++ b/README.md @@ -212,6 +212,9 @@ COMMISSION_PROMPTPAY_VALUE COMMISSION_RECEIVER_ACCOUNT_NUMBER SLIP2GO_VERIFY_URL SLIP2GO_API_SECRET +WEB_PUSH_PUBLIC_KEY +WEB_PUSH_PRIVATE_KEY +WEB_PUSH_SUBJECT DISCORD_BOT_TOKEN DISCORD_CHANNEL_ID ``` @@ -235,6 +238,13 @@ view it. Each checkout accepts payment for one hour after creation. The outbox worker removes expired unpaid checkouts; paid tickets remain available. Apply the commission database migration before enabling checkout. +Commission message notifications require a stable VAPID key pair and subject +(`bunx web-push generate-vapid-keys --json`). Set the three `WEB_PUSH_*` values +in the web deployment secret and apply the push-subscription migration before +enabling notifications. Users opt in from their ticket page. Browser push can +arrive after tabs close; on iPhone and iPad, the site must be added to the Home +Screen before the browser offers push permission. + Traefik must overwrite `X-Real-Ip` for every request, and the web pods must be reachable only through Traefik before enabling the configured client IP based rate limits. The NetworkPolicy assumes Traefik runs in `kube-system` with the diff --git a/app/admin/commission/page.tsx b/app/admin/commission/page.tsx index 95c21f2..52b32ca 100644 --- a/app/admin/commission/page.tsx +++ b/app/admin/commission/page.tsx @@ -6,6 +6,7 @@ import { getDb } from "@/db"; import { commissionCheckouts, commissionTickets, users } from "@/db/schema"; import { AdminHeader } from "@/components/admin/admin-header"; import { CommissionLiveRefresh } from "@/components/commission/live-refresh"; +import { CommissionPushPermission } from "@/components/commission/push-permission"; import { AdminCommissionAvailabilityControl } from "@/components/commission/admin-availability-control"; import { Badge } from "@/components/ui/badge"; import { Card, CardAction, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; @@ -15,7 +16,8 @@ import { getCommissionAvailability } from "@/lib/commission/availability"; export const instant = false; export default async function AdminCommissionPage({ searchParams }: PageProps<"/admin/commission">) { await connection(); - if (!(await getAdminSession())) redirect("/admin/login"); + const session = await getAdminSession(); + if (!session) redirect("/admin/login"); const query = await searchParams; const rawPage = Number(query.page ?? 1); const page = Number.isInteger(rawPage) && rawPage > 0 ? Math.min(rawPage, 10000) : 1; @@ -25,9 +27,12 @@ export default async function AdminCommissionPage({ searchParams }: PageProps<"/ .innerJoin(users, eq(commissionTickets.userId, users.id)) .orderBy(desc(commissionTickets.status), desc(commissionTickets.updatedAt), desc(commissionTickets.id)) .limit(51).offset((page - 1) * 50), getCommissionAvailability()]); - return
+ return
-

Commission tickets

+
+

Commission tickets

+ +
{tickets.length === 0 &&

ยังไม่มี Ticket

} diff --git a/app/api/commission/push-subscription/route.test.ts b/app/api/commission/push-subscription/route.test.ts new file mode 100644 index 0000000..7b579d2 --- /dev/null +++ b/app/api/commission/push-subscription/route.test.ts @@ -0,0 +1,54 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const requireCommissionUser = vi.fn(); +const limitRequest = vi.fn(); +const insert = vi.fn(); +const values = vi.fn(); +const onConflictDoUpdate = vi.fn(); + +vi.mock("@/lib/commission/server", () => ({ requireCommissionUser })); +vi.mock("@/lib/security/rate-limit", () => ({ limitRequest })); +vi.mock("@/db", () => ({ getDb: () => ({ insert }) })); +vi.mock("@/lib/commission/push", () => ({ + pushPublicKey: () => "public-key", + validPushEndpoint: (value: string) => value.startsWith("https://fcm.googleapis.com/"), +})); + +const { POST } = await import("./route"); +const subscription = { endpoint: "https://fcm.googleapis.com/fcm/send/token", + keys: { p256dh: "a".repeat(87), auth: "b".repeat(22) } }; + +function request(scope: "customer" | "admin", endpoint = subscription.endpoint) { + return new Request("https://guide.sudloh.com/api/commission/push-subscription", { + method: "POST", headers: { Origin: "https://guide.sudloh.com", "Content-Type": "application/json" }, + body: JSON.stringify({ ...subscription, endpoint, scope }), + }); +} + +describe("commission push subscriptions", () => { + beforeEach(() => { + vi.clearAllMocks(); + process.env.BETTER_AUTH_URL = "https://guide.sudloh.com"; + requireCommissionUser.mockResolvedValue({ id: "customer-1", role: "user", emailVerified: true }); + insert.mockReturnValue({ values }); + values.mockReturnValue({ onConflictDoUpdate }); + onConflictDoUpdate.mockResolvedValue(undefined); + }); + + it("rejects customer registration for admin notifications", async () => { + expect((await POST(request("admin"))).status).toBe(403); + expect(insert).not.toHaveBeenCalled(); + }); + + it("rejects a push endpoint outside browser push services", async () => { + expect((await POST(request("customer", "https://internal.example/push"))).status).toBe(400); + expect(insert).not.toHaveBeenCalled(); + }); + + it("stores a subscription for the authenticated customer", async () => { + expect((await POST(request("customer"))).status).toBe(204); + expect(values).toHaveBeenCalledWith(expect.objectContaining({ + endpoint: subscription.endpoint, userId: "customer-1", scope: "customer", + })); + }); +}); diff --git a/app/api/commission/push-subscription/route.ts b/app/api/commission/push-subscription/route.ts new file mode 100644 index 0000000..3af73ed --- /dev/null +++ b/app/api/commission/push-subscription/route.ts @@ -0,0 +1,57 @@ +import { and, eq } from "drizzle-orm"; +import * as z from "zod"; +import { getDb } from "@/db"; +import { commissionPushSubscriptions } from "@/db/schema"; +import { pushPublicKey, validPushEndpoint } from "@/lib/commission/push"; +import { requireCommissionUser } from "@/lib/commission/server"; +import { errorResponse, HttpError, readJson, requireSameOrigin } from "@/lib/security/http"; +import { limitRequest } from "@/lib/security/rate-limit"; + +const subscriptionSchema = z.object({ + endpoint: z.string().max(2048), + keys: z.object({ p256dh: z.string().regex(/^[A-Za-z0-9_-]{50,200}$/), + auth: z.string().regex(/^[A-Za-z0-9_-]{10,100}$/) }), + scope: z.enum(["customer", "admin"]), +}); + +export async function GET() { + try { + await requireCommissionUser(); + const publicKey = pushPublicKey(); + if (!publicKey) throw new HttpError(503, "push-not-configured"); + return Response.json({ publicKey }, { headers: { "Cache-Control": "no-store" } }); + } catch (cause) { return errorResponse(cause); } +} + +export async function POST(request: Request) { + try { + requireSameOrigin(request); + const user = await requireCommissionUser(); + if (!pushPublicKey()) throw new HttpError(503, "push-not-configured"); + await limitRequest("commission-push-subscription", user.id, 60); + const parsed = subscriptionSchema.safeParse(await readJson(request, 4096)); + if (!parsed.success || !validPushEndpoint(parsed.data.endpoint)) + throw new HttpError(400, "invalid-push-subscription"); + const { endpoint, keys, scope } = parsed.data; + if (scope === "admin" && (user.role !== "admin" || !user.emailVerified)) + throw new HttpError(403, "forbidden"); + await getDb().insert(commissionPushSubscriptions).values({ + endpoint, userId: user.id, scope, p256dh: keys.p256dh, auth: keys.auth, + }).onConflictDoUpdate({ target: commissionPushSubscriptions.endpoint, + set: { userId: user.id, scope, p256dh: keys.p256dh, auth: keys.auth } }); + return new Response(null, { status: 204 }); + } catch (cause) { return errorResponse(cause); } +} + +export async function DELETE(request: Request) { + try { + requireSameOrigin(request); + const user = await requireCommissionUser(); + const parsed = z.object({ endpoint: z.string().max(2048) }).safeParse(await readJson(request, 4096)); + if (!parsed.success) throw new HttpError(400, "invalid-push-subscription"); + await getDb().delete(commissionPushSubscriptions).where(and( + eq(commissionPushSubscriptions.endpoint, parsed.data.endpoint), + eq(commissionPushSubscriptions.userId, user.id))); + return new Response(null, { status: 204 }); + } catch (cause) { return errorResponse(cause); } +} diff --git a/app/api/commission/tickets/[id]/messages/route.ts b/app/api/commission/tickets/[id]/messages/route.ts index 4ff4c52..0527594 100644 --- a/app/api/commission/tickets/[id]/messages/route.ts +++ b/app/api/commission/tickets/[id]/messages/route.ts @@ -1,6 +1,9 @@ import { eq } from "drizzle-orm"; +import { after } from "next/server"; import { getDb } from "@/db"; import { commissionMessages, commissionTickets } from "@/db/schema"; +import type { CommissionMessageEvent } from "@/lib/commission/message-event"; +import { sendCommissionMessagePush } from "@/lib/commission/push"; import { notifyCommission } from "@/lib/commission/server"; import { authorizeTicket } from "@/lib/commission/tickets"; import { getMediaStorage } from "@/lib/media/storage"; @@ -48,7 +51,15 @@ export async function POST(request: Request, context: RouteContext<"/api/commiss if (imageObjectKey) await (await getMediaStorage()).delete(imageObjectKey).catch(() => undefined); throw cause; } - await notifyCommission(id, ticket.userId); + const message: CommissionMessageEvent = { messageId, ticketId: id, + ticketTitle: ticket.title || `Ticket #${id.slice(0, 8)}`, + authorId: user.id, authorName: user.name, text: body || null }; + await notifyCommission(id, ticket.userId, `message:${JSON.stringify(message)}`); + after(() => sendCommissionMessagePush({ id: messageId, ticketId: id, + ticketTitle: message.ticketTitle, customerId: ticket.userId, authorId: user.id, + authorName: user.name, text: body || null }).catch(() => { + console.error("Commission push delivery failed"); + })); return Response.json({ ok: true, messageId }, { status: 201 }); }); } catch (cause) { return errorResponse(cause); } diff --git a/app/commission/tickets/page.tsx b/app/commission/tickets/page.tsx index e5f4645..7e96d3f 100644 --- a/app/commission/tickets/page.tsx +++ b/app/commission/tickets/page.tsx @@ -5,6 +5,7 @@ import { connection } from "next/server"; import { getDb } from "@/db"; import { commissionCheckouts, commissionTickets } from "@/db/schema"; import { CommissionLiveRefresh } from "@/components/commission/live-refresh"; +import { CommissionPushPermission } from "@/components/commission/push-permission"; import { CommissionSignOut } from "@/components/commission/sign-out"; import { SiteHeader } from "@/components/public/site-header"; import { Badge } from "@/components/ui/badge"; @@ -28,13 +29,14 @@ export default async function CommissionTicketsPage() { gt(commissionCheckouts.createdAt, new Date(checkoutNow() - CHECKOUT_DURATION_MS)))) .orderBy(desc(commissionCheckouts.createdAt)).limit(20), ]); - return
+ return

Ticket ของฉัน

สร้างคำขอเพิ่ม + {pending.length > 0 &&

รอชำระเงิน

} {pending.map((checkout) => รอชำระเงิน - ฿{checkout.amount} diff --git a/app/manifest.ts b/app/manifest.ts new file mode 100644 index 0000000..b1781f7 --- /dev/null +++ b/app/manifest.ts @@ -0,0 +1,12 @@ +import type { MetadataRoute } from "next"; + +export default function manifest(): MetadataRoute.Manifest { + return { + id: "/", + name: "Buzz Sheet", + short_name: "Buzz Sheet", + start_url: "/commission/tickets", + display: "standalone", + icons: [{ src: "/icon.png", sizes: "any", type: "image/png" }], + }; +} diff --git a/bun.lock b/bun.lock index 95c889d..77b6db4 100644 --- a/bun.lock +++ b/bun.lock @@ -48,6 +48,7 @@ "sonner": "^2.0.8", "tailwind-merge": "^3.6.0", "tw-animate-css": "^1.4.0", + "web-push": "^3.6.7", "zod": "^4.4.3", }, "devDependencies": { @@ -58,6 +59,7 @@ "@types/react": "^19", "@types/react-dom": "^19", "@types/sanitize-html": "^2.16.1", + "@types/web-push": "^3.6.4", "@vitest/coverage-v8": "^4.1.11", "drizzle-kit": "0.31.11", "eslint": "^9", @@ -707,6 +709,8 @@ "@types/validate-npm-package-name": ["@types/validate-npm-package-name@4.0.2", "", {}, "sha512-lrpDziQipxCEeK5kWxvljWYhUvOiB2A9izZd9B2AFarYAkqZshb4lPbRs7zKEic6eGtH8V/2qJW+dPp9OtF6bw=="], + "@types/web-push": ["@types/web-push@3.6.4", "", { "dependencies": { "@types/node": "*" } }, "sha512-GnJmSr40H3RAnj0s34FNTcJi1hmWFV5KXugE0mYWnYhgTAHLJ/dJKAwDmvPJYMke0RplY2XE9LnM4hqSqKIjhQ=="], + "@types/ws": ["@types/ws@8.18.1", "", { "dependencies": { "@types/node": "*" } }, "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg=="], "@typescript-eslint/eslint-plugin": ["@typescript-eslint/eslint-plugin@8.68.0", "", { "dependencies": { "@eslint-community/regexpp": "^4.12.2", "@typescript-eslint/scope-manager": "8.68.0", "@typescript-eslint/type-utils": "8.68.0", "@typescript-eslint/utils": "8.68.0", "@typescript-eslint/visitor-keys": "8.68.0", "ignore": "^7.0.5", "natural-compare": "^1.4.0", "ts-api-utils": "^2.5.0" }, "peerDependencies": { "@typescript-eslint/parser": "^8.68.0", "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-WASHDpCm6qO5jj9g1a+8NiW5+GCkAyLReR56/4VruYmNgfUmqpxOfZ2Yfb8xGfJPWv5Qi6LSD8sXdces3vbp/Q=="], @@ -797,6 +801,8 @@ "acorn-jsx": ["acorn-jsx@5.3.2", "", { "peerDependencies": { "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ=="], + "agent-base": ["agent-base@7.1.4", "", {}, "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ=="], + "ajv": ["ajv@6.15.0", "", { "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw=="], "ajv-formats": ["ajv-formats@3.0.1", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ=="], @@ -829,6 +835,8 @@ "arraybuffer.prototype.slice": ["arraybuffer.prototype.slice@1.0.4", "", { "dependencies": { "array-buffer-byte-length": "^1.0.1", "call-bind": "^1.0.8", "define-properties": "^1.2.1", "es-abstract": "^1.23.5", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.6", "is-array-buffer": "^3.0.4" } }, "sha512-BNoCY6SXXPQ7gF2opIP4GBE+Xw7U+pHMYKuzjgCN3GwiaIR09UUeKfheyIry77QtrCBlC0KK0q5/TER/tYh3PQ=="], + "asn1.js": ["asn1.js@5.4.1", "", { "dependencies": { "bn.js": "^4.0.0", "inherits": "^2.0.1", "minimalistic-assert": "^1.0.0", "safer-buffer": "^2.1.0" } }, "sha512-+I//4cYPccV8LdmBLiX8CYvf9Sp3vQsrqu2QNXRcrbiWvcx/UdlFiqUJJzxRQxgsZmvhXhn4cSKeSmoFjVdupA=="], + "assertion-error": ["assertion-error@2.0.1", "", {}, "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA=="], "ast-types": ["ast-types@0.16.1", "", { "dependencies": { "tslib": "^2.0.1" } }, "sha512-6t10qk83GOG8p0vKmaCr8eiilZwO171AvbROMtvvNiwrTly62t+7XkA8RdIIVbpMhCASAsxgAzdRSwh6nw/5Dg=="], @@ -859,6 +867,8 @@ "better-call": ["better-call@1.4.0", "", { "dependencies": { "@better-auth/utils": "^0.5.0", "@better-fetch/fetch": "^1.3.1", "rou3": "^0.9.1", "set-cookie-parser": "^3.1.2" }, "peerDependencies": { "zod": "^4.0.0" }, "optionalPeers": ["zod"] }, "sha512-bBKOT4vv1kZLDgxVePdilk/Jwkn+dtRRsmi3DzHcDP+WnswyVl6dR59l2HEeP/0cB+bDoopASAesWDPIdd/zZA=="], + "bn.js": ["bn.js@4.12.5", "", {}, "sha512-3aRg6/JxfffFD+OlOjOFR3Vo79l39ooBTFucxx+MT3dhCtzn3EmiUPQo+6/OZuI2jbXi3YKgmiTFBgChQMwIRQ=="], + "body-parser": ["body-parser@2.3.0", "", { "dependencies": { "bytes": "^3.1.2", "content-type": "^2.0.0", "debug": "^4.4.3", "http-errors": "^2.0.1", "iconv-lite": "^0.7.2", "on-finished": "^2.4.1", "qs": "^6.15.2", "raw-body": "^3.0.2", "type-is": "^2.1.0" } }, "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw=="], "brace-expansion": ["brace-expansion@1.1.18", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw=="], @@ -867,6 +877,8 @@ "browserslist": ["browserslist@4.28.8", "", { "dependencies": { "baseline-browser-mapping": "^2.11.12", "caniuse-lite": "^1.0.30001809", "electron-to-chromium": "^1.5.402", "node-releases": "^2.0.53", "update-browserslist-db": "^1.3.0" }, "bin": { "browserslist": "cli.js" } }, "sha512-V2NpofLblG64mfOtSgDhOJESZEGogzDMBv/q+W6oc4LXWP/q75eOXoOaaOu1EOadB9U4Bwx/e0yzbvwKH8zalA=="], + "buffer-equal-constant-time": ["buffer-equal-constant-time@1.0.1", "", {}, "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA=="], + "buffer-from": ["buffer-from@1.1.2", "", {}, "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ=="], "bun-types": ["bun-types@1.4.0", "", { "dependencies": { "@types/node": "*" } }, "sha512-iIKw23BspnQQYd3prITOBxeUsxBHnwzX6YJfGMuNOZzeNcMmVqzIIVGRm1l69ogaPQmb4wB6BN8mA5bE9YuC5Q=="], @@ -1043,6 +1055,8 @@ "dunder-proto": ["dunder-proto@1.0.1", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="], + "ecdsa-sig-formatter": ["ecdsa-sig-formatter@1.0.11", "", { "dependencies": { "safe-buffer": "^5.0.1" } }, "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ=="], + "ee-first": ["ee-first@1.1.1", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="], "electron-to-chromium": ["electron-to-chromium@1.5.416", "", {}, "sha512-K6bvB2BjnNrugtIih6ewlbBI9DXa976jIdiIlRLHhBoEI9a4JaQjjHyF+A1IQI543aQYR4LnmOrT/K5fZj0aPA=="], @@ -1257,6 +1271,10 @@ "http-errors": ["http-errors@2.0.1", "", { "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", "setprototypeof": "~1.2.0", "statuses": "~2.0.2", "toidentifier": "~1.0.1" } }, "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ=="], + "http_ece": ["http_ece@1.2.0", "", {}, "sha512-JrF8SSLVmcvc5NducxgyOrKXe3EsyHMgBFgSaIUGmArKe+rwr0uphRkRXvwiom3I+fpIfoItveHrfudL8/rxuA=="], + + "https-proxy-agent": ["https-proxy-agent@7.0.6", "", { "dependencies": { "agent-base": "^7.1.2", "debug": "4" } }, "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw=="], + "human-signals": ["human-signals@8.0.1", "", {}, "sha512-eKCa6bwnJhvxj14kZk5NCPc6Hb6BdsU9DZcOnmQKSnO1VKrfV0zCvtttPZUsBvjmNDn8rpcJfpwSYnHBjc95MQ=="], "iconv-lite": ["iconv-lite@0.7.3", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ=="], @@ -1403,6 +1421,10 @@ "jsx-ast-utils": ["jsx-ast-utils@3.3.5", "", { "dependencies": { "array-includes": "^3.1.6", "array.prototype.flat": "^1.3.1", "object.assign": "^4.1.4", "object.values": "^1.1.6" } }, "sha512-ZZow9HBI5O6EPgSJLUb8n2NKgmVWTwCvHGwFuJlMjvLFqlGG6pjirPhtdsseaLZjSibD8eegzmYpUZwoIlj2cQ=="], + "jwa": ["jwa@2.0.1", "", { "dependencies": { "buffer-equal-constant-time": "^1.0.1", "ecdsa-sig-formatter": "1.0.11", "safe-buffer": "^5.0.1" } }, "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg=="], + + "jws": ["jws@4.0.1", "", { "dependencies": { "jwa": "^2.0.1", "safe-buffer": "^5.0.1" } }, "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA=="], + "keyv": ["keyv@4.5.4", "", { "dependencies": { "json-buffer": "3.0.1" } }, "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw=="], "kleur": ["kleur@4.1.5", "", {}, "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ=="], @@ -1489,6 +1511,8 @@ "mimic-function": ["mimic-function@5.0.1", "", {}, "sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA=="], + "minimalistic-assert": ["minimalistic-assert@1.0.1", "", {}, "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A=="], + "minimatch": ["minimatch@3.1.5", "", { "dependencies": { "brace-expansion": "^1.1.7" } }, "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w=="], "minimist": ["minimist@1.2.8", "", {}, "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA=="], @@ -1715,6 +1739,8 @@ "safe-array-concat": ["safe-array-concat@1.1.4", "", { "dependencies": { "call-bind": "^1.0.9", "call-bound": "^1.0.4", "get-intrinsic": "^1.3.0", "has-symbols": "^1.1.0", "isarray": "^2.0.5" } }, "sha512-wtZlHyOje6OZTGqAoaDKxFkgRtkF9CnHAVnCHKfuj200wAgL+bSJhdsCD2l0Qx/2ekEXjPWcyKkfGb5CPboslg=="], + "safe-buffer": ["safe-buffer@5.2.1", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="], + "safe-push-apply": ["safe-push-apply@1.0.0", "", { "dependencies": { "es-errors": "^1.3.0", "isarray": "^2.0.5" } }, "sha512-iKE9w/Z7xCzUMIZqdBsp6pEQvwuEebH4vdpjcDWnyzaI6yl6O9FHvVpmGelvEHNsoY6wGblkxR6Zty/h00WiSA=="], "safe-regex-test": ["safe-regex-test@1.1.0", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "is-regex": "^1.2.1" } }, "sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw=="], @@ -1915,6 +1941,8 @@ "w3c-keyname": ["w3c-keyname@2.2.8", "", {}, "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ=="], + "web-push": ["web-push@3.6.7", "", { "dependencies": { "asn1.js": "^5.3.0", "http_ece": "1.2.0", "https-proxy-agent": "^7.0.0", "jws": "^4.0.0", "minimist": "^1.2.5" }, "bin": { "web-push": "src/cli.js" } }, "sha512-OpiIUe8cuGjrj3mMBFWY+e4MMIkW3SVT+7vEIjvD9kejGUypv8GPDf84JdPWskK8zMRIJ6xYGm+Kxr8YkPyA0A=="], + "which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="], "which-boxed-primitive": ["which-boxed-primitive@1.1.1", "", { "dependencies": { "is-bigint": "^1.1.0", "is-boolean-object": "^1.2.1", "is-number-object": "^1.1.1", "is-string": "^1.1.1", "is-symbol": "^1.1.1" } }, "sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA=="], diff --git a/components/admin/admin-header.tsx b/components/admin/admin-header.tsx index 2d37a35..ed4f20f 100644 --- a/components/admin/admin-header.tsx +++ b/components/admin/admin-header.tsx @@ -17,6 +17,7 @@ import { import { Button } from "@/components/ui/button"; import { authClient } from "@/lib/auth/client"; +import { unsubscribeCommissionPush } from "@/components/commission/push-permission"; export function AdminHeader() { const pathname = usePathname(); @@ -106,16 +107,17 @@ export function AdminHeader() { variant="ghost" size="icon-sm" aria-label="ออกจากระบบ" - onClick={() => - authClient.signOut({ + onClick={async () => { + await unsubscribeCommissionPush().catch(() => undefined); + await authClient.signOut({ fetchOptions: { onSuccess: () => { router.push("/admin/login"); router.refresh(); }, }, - }) - } + }); + }} > diff --git a/components/commission/live-refresh.tsx b/components/commission/live-refresh.tsx index c76f7b1..d9e1946 100644 --- a/components/commission/live-refresh.tsx +++ b/components/commission/live-refresh.tsx @@ -2,15 +2,31 @@ import { useEffect } from "react"; import { useRouter } from "next/navigation"; +import { parseCommissionMessageEvent } from "@/lib/commission/message-event"; -export function CommissionLiveRefresh({ endpoint }: { endpoint: string }) { +export function CommissionLiveRefresh({ endpoint, userId }: { endpoint: string; userId: string }) { const router = useRouter(); useEffect(() => { + const originalTitle = document.title; + let managedTitle = ""; + let unread = 0; const source = new EventSource(endpoint); - const refresh = () => router.refresh(); + const refresh = (event: Event) => { + const message = parseCommissionMessageEvent((event as MessageEvent).data); + if (message && message.authorId !== userId) { + unread += 1; + managedTitle = `(${unread}) ${message.ticketTitle}`; + document.title = managedTitle; + } + router.refresh(); + }; + const opened = () => router.refresh(); source.addEventListener("changed", refresh); - source.addEventListener("open", refresh); - return () => { source.removeEventListener("changed", refresh); source.removeEventListener("open", refresh); source.close(); }; - }, [endpoint, router]); + source.addEventListener("open", opened); + return () => { + source.removeEventListener("changed", refresh); source.removeEventListener("open", opened); source.close(); + if (managedTitle && document.title === managedTitle) document.title = originalTitle; + }; + }, [endpoint, userId, router]); return null; } diff --git a/components/commission/push-permission.tsx b/components/commission/push-permission.tsx new file mode 100644 index 0000000..5c590e5 --- /dev/null +++ b/components/commission/push-permission.tsx @@ -0,0 +1,90 @@ +"use client"; + +import { useEffect, useState } from "react"; +import { Bell, BellOff } from "lucide-react"; +import { Button } from "@/components/ui/button"; + +type State = "loading" | "off" | "on" | "blocked" | "unavailable"; + +export async function unsubscribeCommissionPush() { + if (!("serviceWorker" in navigator)) return; + const registration = await navigator.serviceWorker.getRegistration("/"); + const subscription = await registration?.pushManager.getSubscription(); + if (!subscription) return; + await fetch("/api/commission/push-subscription", { method: "DELETE", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ endpoint: subscription.endpoint }) }).catch(() => undefined); + await subscription.unsubscribe(); +} + +export function CommissionPushPermission({ scope }: { scope: "customer" | "admin" }) { + const [state, setState] = useState("loading"); + const [publicKey, setPublicKey] = useState(""); + const [error, setError] = useState(""); + + useEffect(() => { + let active = true; + void (async () => { + if (!("Notification" in window) || !("serviceWorker" in navigator) || + !("PushManager" in window) || !window.isSecureContext) { + setState("unavailable"); return; + } + const response = await fetch("/api/commission/push-subscription", { cache: "no-store" }); + if (!response.ok) throw new Error(); + const result = await response.json() as { publicKey: string }; + if (!active) return; + setPublicKey(result.publicKey); + if (Notification.permission === "denied") { setState("blocked"); return; } + if (Notification.permission !== "granted") { setState("off"); return; } + const registration = await navigator.serviceWorker.register("/commission-push-sw.js", { scope: "/" }); + const subscription = await registration.pushManager.getSubscription(); + if (subscription) { + const saved = await fetch("/api/commission/push-subscription", { method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ ...subscription.toJSON(), scope }) }); + if (!saved.ok) throw new Error(); + } + if (active) setState(subscription ? "on" : "off"); + })().catch(() => { if (active) setState("unavailable"); }); + return () => { active = false; }; + }, [scope]); + + async function toggle() { + const previousState = state; + setError(""); setState("loading"); + try { + if (Notification.permission === "granted" && state === "on") { + await unsubscribeCommissionPush(); + setState("off"); + return; + } + if (await Notification.requestPermission() !== "granted") { + setState(Notification.permission === "denied" ? "blocked" : "off"); + return; + } + const registration = await navigator.serviceWorker.register("/commission-push-sw.js", { scope: "/" }); + const subscription = await registration.pushManager.subscribe({ userVisibleOnly: true, + applicationServerKey: publicKey }); + const response = await fetch("/api/commission/push-subscription", { method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ ...subscription.toJSON(), scope }) }); + if (!response.ok) { await subscription.unsubscribe(); throw new Error(); } + setState("on"); + } catch { + setState(previousState === "on" ? "on" : "off"); + setError(`${previousState === "on" ? "ปิด" : "เปิด"}การแจ้งเตือนไม่สำเร็จ กรุณาลองอีกครั้ง`); + } + } + + if (state === "unavailable") return + การแจ้งเตือนไม่พร้อมใช้งานบนเบราว์เซอร์นี้ (iPhone/iPad: เพิ่มเว็บไซต์ไปยังหน้าจอโฮมก่อน) + ; + if (state === "blocked") return เบราว์เซอร์บล็อกการแจ้งเตือนอยู่; + return
+ + {error && {error}} +
; +} diff --git a/components/commission/sign-out.tsx b/components/commission/sign-out.tsx index 4c3f6ae..11f36bd 100644 --- a/components/commission/sign-out.tsx +++ b/components/commission/sign-out.tsx @@ -4,10 +4,12 @@ import { useRouter } from "next/navigation"; import { LogOutIcon } from "lucide-react"; import { Button } from "@/components/ui/button"; import { authClient } from "@/lib/auth/client"; +import { unsubscribeCommissionPush } from "./push-permission"; export function CommissionSignOut() { const router = useRouter(); return
diff --git a/db/schema.ts b/db/schema.ts index 39131ae..f109fe0 100644 --- a/db/schema.ts +++ b/db/schema.ts @@ -201,6 +201,15 @@ export const commissionPayments = commissionSchema.table("payment", { uniqueIndex("commission_payment_trans_ref_unique").on(table.transRef), ]); +export const commissionPushSubscriptions = commissionSchema.table("push_subscription", { + endpoint: text("endpoint").primaryKey(), + userId: text("user_id").notNull().references(() => users.id, { onDelete: "cascade" }), + scope: varchar("scope", { length: 8 }).notNull(), + p256dh: text("p256dh").notNull(), + auth: text("auth").notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), +}, (table) => [index("commission_push_subscription_user_idx").on(table.userId)]); + export const commissionMessages = commissionSchema.table("message", { id: uuid("id").defaultRandom().primaryKey(), ticketId: uuid("ticket_id").notNull().references(() => commissionTickets.id), diff --git a/drizzle/0068_concerned_union_jack.sql b/drizzle/0068_concerned_union_jack.sql new file mode 100644 index 0000000..eda39d9 --- /dev/null +++ b/drizzle/0068_concerned_union_jack.sql @@ -0,0 +1,11 @@ +CREATE TABLE "commission"."push_subscription" ( + "endpoint" text PRIMARY KEY NOT NULL, + "user_id" text NOT NULL, + "scope" varchar(8) NOT NULL, + "p256dh" text NOT NULL, + "auth" text NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +ALTER TABLE "commission"."push_subscription" ADD CONSTRAINT "push_subscription_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "auth"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +CREATE INDEX "commission_push_subscription_user_idx" ON "commission"."push_subscription" USING btree ("user_id"); \ No newline at end of file diff --git a/drizzle/meta/0068_snapshot.json b/drizzle/meta/0068_snapshot.json new file mode 100644 index 0000000..8f12054 --- /dev/null +++ b/drizzle/meta/0068_snapshot.json @@ -0,0 +1,3967 @@ +{ + "id": "d800c009-6052-46b1-a739-38c974362f76", + "prevId": "ba59f229-d62d-41e0-948b-ae9e7e4d622e", + "version": "7", + "dialect": "postgresql", + "tables": { + "auth.account": { + "name": "account", + "schema": "auth", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "issuer": { + "name": "issuer", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "account_id": { + "name": "account_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "access_token": { + "name": "access_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_token": { + "name": "refresh_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "id_token": { + "name": "id_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "access_token_expires_at": { + "name": "access_token_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "refresh_token_expires_at": { + "name": "refresh_token_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "account_provider_unique": { + "name": "account_provider_unique", + "columns": [ + { + "expression": "provider_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "account_user_id_idx": { + "name": "account_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "account_user_id_user_id_fk": { + "name": "account_user_id_user_id_fk", + "tableFrom": "account", + "tableTo": "user", + "schemaTo": "auth", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "guides.artifact_condition": { + "name": "artifact_condition", + "schema": "guides", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "guide_id": { + "name": "guide_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "varchar(120)", + "primaryKey": false, + "notNull": false + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "artifact_condition_order_idx": { + "name": "artifact_condition_order_idx", + "columns": [ + { + "expression": "guide_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sort_order", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "artifact_condition_guide_id_guide_id_fk": { + "name": "artifact_condition_guide_id_guide_id_fk", + "tableFrom": "artifact_condition", + "tableTo": "guide", + "schemaTo": "guides", + "columnsFrom": [ + "guide_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "guides.artifact_group": { + "name": "artifact_group", + "schema": "guides", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "condition_id": { + "name": "condition_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "artifact_group_order_idx": { + "name": "artifact_group_order_idx", + "columns": [ + { + "expression": "condition_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sort_order", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "artifact_group_condition_id_artifact_condition_id_fk": { + "name": "artifact_group_condition_id_artifact_condition_id_fk", + "tableFrom": "artifact_group", + "tableTo": "artifact_condition", + "schemaTo": "guides", + "columnsFrom": [ + "condition_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "guides.artifact_profile": { + "name": "artifact_profile", + "schema": "guides", + "columns": { + "guide_id": { + "name": "guide_id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "sands": { + "name": "sands", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "goblet": { + "name": "goblet", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "circlet": { + "name": "circlet", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "substats": { + "name": "substats", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "recommended_conditions": { + "name": "recommended_conditions", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "targets": { + "name": "targets", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "target_conditions": { + "name": "target_conditions", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "talents": { + "name": "talents", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "artifact_profile_guide_id_guide_id_fk": { + "name": "artifact_profile_guide_id_guide_id_fk", + "tableFrom": "artifact_profile", + "tableTo": "guide", + "schemaTo": "guides", + "columnsFrom": [ + "guide_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "guides.artifact_recommendation": { + "name": "artifact_recommendation", + "schema": "guides", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "group_id": { + "name": "group_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "first_artifact_key": { + "name": "first_artifact_key", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true + }, + "second_artifact_key": { + "name": "second_artifact_key", + "type": "varchar(64)", + "primaryKey": false, + "notNull": false + }, + "percent": { + "name": "percent", + "type": "numeric(8, 2)", + "primaryKey": false, + "notNull": true + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "artifact_recommendation_order_idx": { + "name": "artifact_recommendation_order_idx", + "columns": [ + { + "expression": "group_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sort_order", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "artifact_recommendation_group_id_artifact_group_id_fk": { + "name": "artifact_recommendation_group_id_artifact_group_id_fk", + "tableFrom": "artifact_recommendation", + "tableTo": "artifact_group", + "schemaTo": "guides", + "columnsFrom": [ + "group_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.audit_log": { + "name": "audit_log", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "bigint", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "audit_log_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "9223372036854775807", + "cache": "1", + "cycle": false + } + }, + "author_id": { + "name": "author_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "author": { + "name": "author", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "details": { + "name": "details", + "type": "jsonb", + "primaryKey": false, + "notNull": false, + "default": "'{}'::jsonb" + }, + "time": { + "name": "time", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "audit_log_time_idx": { + "name": "audit_log_time_idx", + "columns": [ + { + "expression": "time", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "audit_log_author_time_idx": { + "name": "audit_log_author_time_idx", + "columns": [ + { + "expression": "author_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "time", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "catalog.artifact": { + "name": "artifact", + "schema": "catalog", + "columns": { + "key": { + "name": "key", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "rarity": { + "name": "rarity", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "image_key": { + "name": "image_key", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "catalog_artifact_name_idx": { + "name": "catalog_artifact_name_idx", + "columns": [ + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "artifact_key_pk": { + "name": "artifact_key_pk", + "columns": [ + "key" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "catalog.character": { + "name": "character", + "schema": "catalog", + "columns": { + "key": { + "name": "key", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "element": { + "name": "element", + "type": "varchar(48)", + "primaryKey": false, + "notNull": false + }, + "rarity": { + "name": "rarity", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "weapon_type": { + "name": "weapon_type", + "type": "varchar(64)", + "primaryKey": false, + "notNull": false + }, + "image_key": { + "name": "image_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "element_icon_key": { + "name": "element_icon_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "coop_image_key": { + "name": "coop_image_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name_card_image_key": { + "name": "name_card_image_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "constellations": { + "name": "constellations", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "talents": { + "name": "talents", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "ascension": { + "name": "ascension", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "leveling": { + "name": "leveling", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "base_stats": { + "name": "base_stats", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + } + }, + "indexes": { + "catalog_character_name_idx": { + "name": "catalog_character_name_idx", + "columns": [ + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "character_key_pk": { + "name": "character_key_pk", + "columns": [ + "key" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "catalog.material": { + "name": "material", + "schema": "catalog", + "columns": { + "key": { + "name": "key", + "type": "varchar(64)", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "rarity": { + "name": "rarity", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "varchar(64)", + "primaryKey": false, + "notNull": false + }, + "image_key": { + "name": "image_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "catalog_material_name_idx": { + "name": "catalog_material_name_idx", + "columns": [ + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "catalog.weapon": { + "name": "weapon", + "schema": "catalog", + "columns": { + "key": { + "name": "key", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "rarity": { + "name": "rarity", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "weapon_type": { + "name": "weapon_type", + "type": "varchar(64)", + "primaryKey": false, + "notNull": false + }, + "image_key": { + "name": "image_key", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "catalog_weapon_name_idx": { + "name": "catalog_weapon_name_idx", + "columns": [ + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "weapon_key_pk": { + "name": "weapon_key_pk", + "columns": [ + "key" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "commission.checkout": { + "name": "checkout", + "schema": "commission", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "request": { + "name": "request", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "amount_baht": { + "name": "amount_baht", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "commission_checkout_user_idx": { + "name": "commission_checkout_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "checkout_user_id_user_id_fk": { + "name": "checkout_user_id_user_id_fk", + "tableFrom": "checkout", + "tableTo": "user", + "schemaTo": "auth", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "commission.message": { + "name": "message", + "schema": "commission", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "ticket_id": { + "name": "ticket_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "author_id": { + "name": "author_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "image_object_key": { + "name": "image_object_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "image_mime_type": { + "name": "image_mime_type", + "type": "varchar(32)", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "commission_message_ticket_time_idx": { + "name": "commission_message_ticket_time_idx", + "columns": [ + { + "expression": "ticket_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "message_ticket_id_ticket_id_fk": { + "name": "message_ticket_id_ticket_id_fk", + "tableFrom": "message", + "tableTo": "ticket", + "schemaTo": "commission", + "columnsFrom": [ + "ticket_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "message_author_id_user_id_fk": { + "name": "message_author_id_user_id_fk", + "tableFrom": "message", + "tableTo": "user", + "schemaTo": "auth", + "columnsFrom": [ + "author_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "commission.payment": { + "name": "payment", + "schema": "commission", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "checkout_id": { + "name": "checkout_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "ticket_id": { + "name": "ticket_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "reference_id": { + "name": "reference_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "trans_ref": { + "name": "trans_ref", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "amount_baht": { + "name": "amount_baht", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "transferred_at": { + "name": "transferred_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "slip_object_key": { + "name": "slip_object_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slip_mime_type": { + "name": "slip_mime_type", + "type": "varchar(32)", + "primaryKey": false, + "notNull": true + }, + "provider_data": { + "name": "provider_data", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "commission_payment_checkout_unique": { + "name": "commission_payment_checkout_unique", + "columns": [ + { + "expression": "checkout_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "commission_payment_reference_unique": { + "name": "commission_payment_reference_unique", + "columns": [ + { + "expression": "reference_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "commission_payment_trans_ref_unique": { + "name": "commission_payment_trans_ref_unique", + "columns": [ + { + "expression": "trans_ref", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "payment_checkout_id_checkout_id_fk": { + "name": "payment_checkout_id_checkout_id_fk", + "tableFrom": "payment", + "tableTo": "checkout", + "schemaTo": "commission", + "columnsFrom": [ + "checkout_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "payment_ticket_id_ticket_id_fk": { + "name": "payment_ticket_id_ticket_id_fk", + "tableFrom": "payment", + "tableTo": "ticket", + "schemaTo": "commission", + "columnsFrom": [ + "ticket_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "commission.push_subscription": { + "name": "push_subscription", + "schema": "commission", + "columns": { + "endpoint": { + "name": "endpoint", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scope": { + "name": "scope", + "type": "varchar(8)", + "primaryKey": false, + "notNull": true + }, + "p256dh": { + "name": "p256dh", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "auth": { + "name": "auth", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "commission_push_subscription_user_idx": { + "name": "commission_push_subscription_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "push_subscription_user_id_user_id_fk": { + "name": "push_subscription_user_id_user_id_fk", + "tableFrom": "push_subscription", + "tableTo": "user", + "schemaTo": "auth", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "commission.reaction": { + "name": "reaction", + "schema": "commission", + "columns": { + "message_id": { + "name": "message_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "emoji": { + "name": "emoji", + "type": "varchar(16)", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "reaction_message_id_message_id_fk": { + "name": "reaction_message_id_message_id_fk", + "tableFrom": "reaction", + "tableTo": "message", + "schemaTo": "commission", + "columnsFrom": [ + "message_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "reaction_user_id_user_id_fk": { + "name": "reaction_user_id_user_id_fk", + "tableFrom": "reaction", + "tableTo": "user", + "schemaTo": "auth", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "reaction_message_id_user_id_emoji_pk": { + "name": "reaction_message_id_user_id_emoji_pk", + "columns": [ + "message_id", + "user_id", + "emoji" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "commission.settings": { + "name": "settings", + "schema": "commission", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true + }, + "is_open": { + "name": "is_open", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "closure_message": { + "name": "closure_message", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "commission.ticket": { + "name": "ticket", + "schema": "commission", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "checkout_id": { + "name": "checkout_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "varchar(80)", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "varchar(16)", + "primaryKey": false, + "notNull": true, + "default": "'open'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "commission_ticket_checkout_unique": { + "name": "commission_ticket_checkout_unique", + "columns": [ + { + "expression": "checkout_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "commission_ticket_user_idx": { + "name": "commission_ticket_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "commission_ticket_status_idx": { + "name": "commission_ticket_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "ticket_checkout_id_checkout_id_fk": { + "name": "ticket_checkout_id_checkout_id_fk", + "tableFrom": "ticket", + "tableTo": "checkout", + "schemaTo": "commission", + "columnsFrom": [ + "checkout_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "ticket_user_id_user_id_fk": { + "name": "ticket_user_id_user_id_fk", + "tableFrom": "ticket", + "tableTo": "user", + "schemaTo": "auth", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "guides.constellation_condition": { + "name": "constellation_condition", + "schema": "guides", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "guide_id": { + "name": "guide_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "varchar(120)", + "primaryKey": false, + "notNull": false + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "constellation_condition_order_idx": { + "name": "constellation_condition_order_idx", + "columns": [ + { + "expression": "guide_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sort_order", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "constellation_condition_guide_id_guide_id_fk": { + "name": "constellation_condition_guide_id_guide_id_fk", + "tableFrom": "constellation_condition", + "tableTo": "guide", + "schemaTo": "guides", + "columnsFrom": [ + "guide_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "guides.constellation_recommendation": { + "name": "constellation_recommendation", + "schema": "guides", + "columns": { + "condition_id": { + "name": "condition_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "level": { + "name": "level", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "detail": { + "name": "detail", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "cumulative_percent": { + "name": "cumulative_percent", + "type": "numeric(8, 2)", + "primaryKey": false, + "notNull": true + }, + "is_great": { + "name": "is_great", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + } + }, + "indexes": {}, + "foreignKeys": { + "constellation_recommendation_condition_id_constellation_condition_id_fk": { + "name": "constellation_recommendation_condition_id_constellation_condition_id_fk", + "tableFrom": "constellation_recommendation", + "tableTo": "constellation_condition", + "schemaTo": "guides", + "columnsFrom": [ + "condition_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "constellation_recommendation_condition_id_level_pk": { + "name": "constellation_recommendation_condition_id_level_pk", + "columns": [ + "condition_id", + "level" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "guides.extra_section_row": { + "name": "extra_section_row", + "schema": "guides", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "section_id": { + "name": "section_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "media_id": { + "name": "media_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "heading": { + "name": "heading", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "body": { + "name": "body", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "percent": { + "name": "percent", + "type": "numeric(8, 2)", + "primaryKey": false, + "notNull": false + }, + "background_color": { + "name": "background_color", + "type": "varchar(7)", + "primaryKey": false, + "notNull": false + }, + "text_color": { + "name": "text_color", + "type": "varchar(7)", + "primaryKey": false, + "notNull": false + }, + "highlights": { + "name": "highlights", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "catalog_items": { + "name": "catalog_items", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "sheet": { + "name": "sheet", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "extra_section_row_order_idx": { + "name": "extra_section_row_order_idx", + "columns": [ + { + "expression": "section_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sort_order", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "extra_section_row_section_id_extra_section_section_id_fk": { + "name": "extra_section_row_section_id_extra_section_section_id_fk", + "tableFrom": "extra_section_row", + "tableTo": "extra_section", + "schemaTo": "guides", + "columnsFrom": [ + "section_id" + ], + "columnsTo": [ + "section_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "extra_section_row_media_id_media_id_fk": { + "name": "extra_section_row_media_id_media_id_fk", + "tableFrom": "extra_section_row", + "tableTo": "media", + "columnsFrom": [ + "media_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "guides.extra_section": { + "name": "extra_section", + "schema": "guides", + "columns": { + "section_id": { + "name": "section_id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "extra_section_section_id_guide_section_id_fk": { + "name": "extra_section_section_id_guide_section_id_fk", + "tableFrom": "extra_section", + "tableTo": "guide_section", + "schemaTo": "guides", + "columnsFrom": [ + "section_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "guides.glossary_alias": { + "name": "glossary_alias", + "schema": "guides", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "kind": { + "name": "kind", + "type": "varchar(16)", + "primaryKey": false, + "notNull": true + }, + "catalog_key": { + "name": "catalog_key", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true + }, + "alias": { + "name": "alias", + "type": "varchar(120)", + "primaryKey": false, + "notNull": true + }, + "normalized_alias": { + "name": "normalized_alias", + "type": "varchar(120)", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "glossary_alias_item_normalized_unique": { + "name": "glossary_alias_item_normalized_unique", + "columns": [ + { + "expression": "kind", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "catalog_key", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "normalized_alias", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "glossary_alias_item_idx": { + "name": "glossary_alias_item_idx", + "columns": [ + { + "expression": "kind", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "catalog_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "guides.guide_poster_bleeding": { + "name": "guide_poster_bleeding", + "schema": "guides", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "guide_id": { + "name": "guide_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "media_id": { + "name": "media_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "amount": { + "name": "amount", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 100 + }, + "scale": { + "name": "scale", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 100 + }, + "blend_mode": { + "name": "blend_mode", + "type": "varchar(32)", + "primaryKey": false, + "notNull": true, + "default": "'multiply'" + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "guide_poster_bleeding_order_idx": { + "name": "guide_poster_bleeding_order_idx", + "columns": [ + { + "expression": "guide_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sort_order", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "guide_poster_bleeding_guide_id_guide_id_fk": { + "name": "guide_poster_bleeding_guide_id_guide_id_fk", + "tableFrom": "guide_poster_bleeding", + "tableTo": "guide", + "schemaTo": "guides", + "columnsFrom": [ + "guide_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "guide_poster_bleeding_media_id_media_id_fk": { + "name": "guide_poster_bleeding_media_id_media_id_fk", + "tableFrom": "guide_poster_bleeding", + "tableTo": "media", + "columnsFrom": [ + "media_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "guides.guide_section": { + "name": "guide_section", + "schema": "guides", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "guide_id": { + "name": "guide_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "varchar(32)", + "primaryKey": false, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "varchar(120)", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "guide_section_slug_unique": { + "name": "guide_section_slug_unique", + "columns": [ + { + "expression": "guide_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "guide_section_order_idx": { + "name": "guide_section_order_idx", + "columns": [ + { + "expression": "guide_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sort_order", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "guide_section_guide_id_guide_id_fk": { + "name": "guide_section_guide_id_guide_id_fk", + "tableFrom": "guide_section", + "tableTo": "guide", + "schemaTo": "guides", + "columnsFrom": [ + "guide_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "guides.guide": { + "name": "guide", + "schema": "guides", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "character_key": { + "name": "character_key", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "varchar(120)", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "overview": { + "name": "overview", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "youtube_urls": { + "name": "youtube_urls", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "cover_media_id": { + "name": "cover_media_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "poster_art_media_id": { + "name": "poster_art_media_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "poster_art_offset_x": { + "name": "poster_art_offset_x", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "poster_art_offset_y": { + "name": "poster_art_offset_y", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "poster_art_scale": { + "name": "poster_art_scale", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 100 + }, + "poster_art_rotation": { + "name": "poster_art_rotation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "poster_top_colors": { + "name": "poster_top_colors", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[\"#000000\",\"#000000\"]'::jsonb" + }, + "poster_bottom_colors": { + "name": "poster_bottom_colors", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[\"#000000\",\"#000000\"]'::jsonb" + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "is_public": { + "name": "is_public", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "published_at": { + "name": "published_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "trashed_at": { + "name": "trashed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "guide_character_key_unique": { + "name": "guide_character_key_unique", + "columns": [ + { + "expression": "character_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "guide_slug_unique": { + "name": "guide_slug_unique", + "columns": [ + { + "expression": "slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "guide_directory_idx": { + "name": "guide_directory_idx", + "columns": [ + { + "expression": "trashed_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sort_order", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "guide_cover_media_id_media_id_fk": { + "name": "guide_cover_media_id_media_id_fk", + "tableFrom": "guide", + "tableTo": "media", + "columnsFrom": [ + "cover_media_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "guide_poster_art_media_id_media_id_fk": { + "name": "guide_poster_art_media_id_media_id_fk", + "tableFrom": "guide", + "tableTo": "media", + "columnsFrom": [ + "poster_art_media_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.media": { + "name": "media", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "object_key": { + "name": "object_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "file_name": { + "name": "file_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "mime_type": { + "name": "mime_type", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true + }, + "byte_size": { + "name": "byte_size", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "checksum": { + "name": "checksum", + "type": "varchar(128)", + "primaryKey": false, + "notNull": false + }, + "width": { + "name": "width", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "height": { + "name": "height", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "varchar(24)", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "current_reference_count": { + "name": "current_reference_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "created_by_id": { + "name": "created_by_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "media_object_key_unique": { + "name": "media_object_key_unique", + "columns": [ + { + "expression": "object_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "media_visibility_idx": { + "name": "media_visibility_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "current_reference_count", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "media_created_by_id_user_id_fk": { + "name": "media_created_by_id_user_id_fk", + "tableFrom": "media", + "tableTo": "user", + "schemaTo": "auth", + "columnsFrom": [ + "created_by_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.outbox_event": { + "name": "outbox_event", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "bigint", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "outbox_event_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "9223372036854775807", + "cache": "1", + "cycle": false + } + }, + "topic": { + "name": "topic", + "type": "varchar(160)", + "primaryKey": false, + "notNull": true + }, + "aggregate_id": { + "name": "aggregate_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "event_type": { + "name": "event_type", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "varchar(24)", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "available_at": { + "name": "available_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "processed_at": { + "name": "processed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "outbox_pending_idx": { + "name": "outbox_pending_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "available_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "auth.session": { + "name": "session", + "schema": "auth", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "ip_address": { + "name": "ip_address", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "impersonated_by": { + "name": "impersonated_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "session_token_unique": { + "name": "session_token_unique", + "columns": [ + { + "expression": "token", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "session_user_id_idx": { + "name": "session_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "session_user_id_user_id_fk": { + "name": "session_user_id_user_id_fk", + "tableFrom": "session", + "tableTo": "user", + "schemaTo": "auth", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "guides.stygian_boss": { + "name": "stygian_boss", + "schema": "guides", + "columns": { + "schedule_id": { + "name": "schedule_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "level": { + "name": "level", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "config_id": { + "name": "config_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "hp": { + "name": "hp", + "type": "numeric(18, 2)", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "mechanics": { + "name": "mechanics", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "recommended_mechanics": { + "name": "recommended_mechanics", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "recommended_mechanic_types": { + "name": "recommended_mechanic_types", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "image_key": { + "name": "image_key", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "stygian_boss_schedule_idx": { + "name": "stygian_boss_schedule_idx", + "columns": [ + { + "expression": "schedule_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "level", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "stygian_boss_schedule_id_stygian_schedule_schedule_id_fk": { + "name": "stygian_boss_schedule_id_stygian_schedule_schedule_id_fk", + "tableFrom": "stygian_boss", + "tableTo": "stygian_schedule", + "schemaTo": "guides", + "columnsFrom": [ + "schedule_id" + ], + "columnsTo": [ + "schedule_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "stygian_boss_schedule_id_level_position_pk": { + "name": "stygian_boss_schedule_id_level_position_pk", + "columns": [ + "schedule_id", + "level", + "position" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "guides.stygian_recommendation_group": { + "name": "stygian_recommendation_group", + "schema": "guides", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "schedule_id": { + "name": "schedule_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "level": { + "name": "level", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "boss_position": { + "name": "boss_position", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "varchar(16)", + "primaryKey": false, + "notNull": true + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "stygian_recommendation_group_order_idx": { + "name": "stygian_recommendation_group_order_idx", + "columns": [ + { + "expression": "schedule_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "level", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "boss_position", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "kind", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sort_order", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "stygian_recommendation_group_schedule_id_stygian_schedule_schedule_id_fk": { + "name": "stygian_recommendation_group_schedule_id_stygian_schedule_schedule_id_fk", + "tableFrom": "stygian_recommendation_group", + "tableTo": "stygian_schedule", + "schemaTo": "guides", + "columnsFrom": [ + "schedule_id" + ], + "columnsTo": [ + "schedule_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "guides.stygian_recommendation_item": { + "name": "stygian_recommendation_item", + "schema": "guides", + "columns": { + "group_id": { + "name": "group_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "varchar(24)", + "primaryKey": false, + "notNull": true + }, + "catalog_key": { + "name": "catalog_key", + "type": "varchar(64)", + "primaryKey": false, + "notNull": false + }, + "weapon_key": { + "name": "weapon_key", + "type": "varchar(64)", + "primaryKey": false, + "notNull": false + }, + "artifact_key": { + "name": "artifact_key", + "type": "varchar(64)", + "primaryKey": false, + "notNull": false + }, + "refinement": { + "name": "refinement", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "constellation_level": { + "name": "constellation_level", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "element": { + "name": "element", + "type": "varchar(24)", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "stygian_recommendation_item_group_id_stygian_recommendation_group_id_fk": { + "name": "stygian_recommendation_item_group_id_stygian_recommendation_group_id_fk", + "tableFrom": "stygian_recommendation_item", + "tableTo": "stygian_recommendation_group", + "schemaTo": "guides", + "columnsFrom": [ + "group_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "stygian_recommendation_item_group_id_position_pk": { + "name": "stygian_recommendation_item_group_id_position_pk", + "columns": [ + "group_id", + "position" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "guides.stygian_schedule": { + "name": "stygian_schedule", + "schema": "guides", + "columns": { + "schedule_id": { + "name": "schedule_id", + "type": "integer", + "primaryKey": true, + "notNull": true + }, + "challenge_name": { + "name": "challenge_name", + "type": "varchar(32)", + "primaryKey": false, + "notNull": true + }, + "schedule_start_time": { + "name": "schedule_start_time", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "schedule_end_time": { + "name": "schedule_end_time", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "guides.team_composition": { + "name": "team_composition", + "schema": "guides", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "guide_id": { + "name": "guide_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "condition_id": { + "name": "condition_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "rotation_seconds": { + "name": "rotation_seconds", + "type": "numeric(8, 2)", + "primaryKey": false, + "notNull": true + }, + "combo": { + "name": "combo", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "team_composition_order_idx": { + "name": "team_composition_order_idx", + "columns": [ + { + "expression": "guide_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sort_order", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "team_composition_guide_id_guide_id_fk": { + "name": "team_composition_guide_id_guide_id_fk", + "tableFrom": "team_composition", + "tableTo": "guide", + "schemaTo": "guides", + "columnsFrom": [ + "guide_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "team_composition_condition_id_team_condition_id_fk": { + "name": "team_composition_condition_id_team_condition_id_fk", + "tableFrom": "team_composition", + "tableTo": "team_condition", + "schemaTo": "guides", + "columnsFrom": [ + "condition_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "guides.team_condition": { + "name": "team_condition", + "schema": "guides", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "guide_id": { + "name": "guide_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "varchar(120)", + "primaryKey": false, + "notNull": false + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "team_condition_order_idx": { + "name": "team_condition_order_idx", + "columns": [ + { + "expression": "guide_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sort_order", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "team_condition_guide_id_guide_id_fk": { + "name": "team_condition_guide_id_guide_id_fk", + "tableFrom": "team_condition", + "tableTo": "guide", + "schemaTo": "guides", + "columnsFrom": [ + "guide_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "guides.team_member": { + "name": "team_member", + "schema": "guides", + "columns": { + "team_id": { + "name": "team_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "character_key": { + "name": "character_key", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true + }, + "weapon_key": { + "name": "weapon_key", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true + }, + "artifact_key": { + "name": "artifact_key", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true + }, + "second_artifact_key": { + "name": "second_artifact_key", + "type": "varchar(64)", + "primaryKey": false, + "notNull": false + }, + "constellation": { + "name": "constellation", + "type": "varchar(8)", + "primaryKey": false, + "notNull": true, + "default": "'0'" + }, + "refinement": { + "name": "refinement", + "type": "varchar(8)", + "primaryKey": false, + "notNull": true, + "default": "'1'" + }, + "damage": { + "name": "damage", + "type": "numeric(18, 2)", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "team_member_team_id_team_composition_id_fk": { + "name": "team_member_team_id_team_composition_id_fk", + "tableFrom": "team_member", + "tableTo": "team_composition", + "schemaTo": "guides", + "columnsFrom": [ + "team_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "team_member_team_id_position_pk": { + "name": "team_member_team_id_position_pk", + "columns": [ + "team_id", + "position" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "auth.user": { + "name": "user", + "schema": "auth", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email_verified": { + "name": "email_verified", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'user'" + }, + "banned": { + "name": "banned", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": false + }, + "ban_reason": { + "name": "ban_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "ban_expires": { + "name": "ban_expires", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "user_email_unique": { + "name": "user_email_unique", + "columns": [ + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "auth.verification": { + "name": "verification", + "schema": "auth", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "identifier": { + "name": "identifier", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "verification_identifier_idx": { + "name": "verification_identifier_idx", + "columns": [ + { + "expression": "identifier", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "guides.weapon_condition": { + "name": "weapon_condition", + "schema": "guides", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "guide_id": { + "name": "guide_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "varchar(120)", + "primaryKey": false, + "notNull": false + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "weapon_condition_order_idx": { + "name": "weapon_condition_order_idx", + "columns": [ + { + "expression": "guide_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sort_order", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "weapon_condition_guide_id_guide_id_fk": { + "name": "weapon_condition_guide_id_guide_id_fk", + "tableFrom": "weapon_condition", + "tableTo": "guide", + "schemaTo": "guides", + "columnsFrom": [ + "guide_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "guides.weapon_recommendation": { + "name": "weapon_recommendation", + "schema": "guides", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "condition_id": { + "name": "condition_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "weapon_key": { + "name": "weapon_key", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true + }, + "refinement": { + "name": "refinement", + "type": "varchar(8)", + "primaryKey": false, + "notNull": true + }, + "overall_percent": { + "name": "overall_percent", + "type": "numeric(8, 2)", + "primaryKey": false, + "notNull": false + }, + "personal_percent": { + "name": "personal_percent", + "type": "numeric(8, 2)", + "primaryKey": false, + "notNull": false + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "weapon_recommendation_order_idx": { + "name": "weapon_recommendation_order_idx", + "columns": [ + { + "expression": "condition_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sort_order", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "weapon_recommendation_condition_id_weapon_condition_id_fk": { + "name": "weapon_recommendation_condition_id_weapon_condition_id_fk", + "tableFrom": "weapon_recommendation", + "tableTo": "weapon_condition", + "schemaTo": "guides", + "columnsFrom": [ + "condition_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index c50c32f..5501544 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -477,6 +477,13 @@ "when": 1790863872049, "tag": "0067_nervous_psylocke", "breakpoints": true + }, + { + "idx": 68, + "version": "7", + "when": 1790915901646, + "tag": "0068_concerned_union_jack", + "breakpoints": true } ] } \ No newline at end of file diff --git a/k8s/base/deployment.yaml b/k8s/base/deployment.yaml index 794e10b..c799844 100644 --- a/k8s/base/deployment.yaml +++ b/k8s/base/deployment.yaml @@ -128,6 +128,24 @@ spec: name: buzz-sheet-env key: COMMISSION_DISCORD_WEBHOOK_URL optional: true + - name: WEB_PUSH_PUBLIC_KEY + valueFrom: + secretKeyRef: + name: buzz-sheet-env + key: WEB_PUSH_PUBLIC_KEY + optional: true + - name: WEB_PUSH_PRIVATE_KEY + valueFrom: + secretKeyRef: + name: buzz-sheet-env + key: WEB_PUSH_PRIVATE_KEY + optional: true + - name: WEB_PUSH_SUBJECT + valueFrom: + secretKeyRef: + name: buzz-sheet-env + key: WEB_PUSH_SUBJECT + optional: true - name: NEXT_SERVER_ACTIONS_ENCRYPTION_KEY valueFrom: secretKeyRef: diff --git a/lib/commission/message-event.test.ts b/lib/commission/message-event.test.ts new file mode 100644 index 0000000..8b9a34d --- /dev/null +++ b/lib/commission/message-event.test.ts @@ -0,0 +1,12 @@ +import { describe, expect, it } from "vitest"; +import { parseCommissionMessageEvent } from "./message-event"; + +describe("commission message events", () => { + it("accepts a new message and ignores other refresh events", () => { + const message = { messageId: "message-1", ticketId: "ticket-1", ticketTitle: "Build help", + authorId: "admin-1", authorName: "Admin", text: "Hello" }; + expect(parseCommissionMessageEvent(`message:${JSON.stringify(message)}`)).toEqual(message); + expect(parseCommissionMessageEvent("changed")).toBeNull(); + expect(parseCommissionMessageEvent("message:not-json")).toBeNull(); + }); +}); diff --git a/lib/commission/message-event.ts b/lib/commission/message-event.ts new file mode 100644 index 0000000..84b6351 --- /dev/null +++ b/lib/commission/message-event.ts @@ -0,0 +1,15 @@ +export type CommissionMessageEvent = { + messageId: string; ticketId: string; ticketTitle: string; authorId: string; + authorName: string; text: string | null; +}; + +export function parseCommissionMessageEvent(value: string): CommissionMessageEvent | null { + if (!value.startsWith("message:")) return null; + try { + const message = JSON.parse(value.slice(8)) as CommissionMessageEvent; + return typeof message.messageId === "string" && typeof message.ticketId === "string" && + typeof message.ticketTitle === "string" && typeof message.authorId === "string" && + typeof message.authorName === "string" && + (typeof message.text === "string" || message.text === null) ? message : null; + } catch { return null; } +} diff --git a/lib/commission/push.test.ts b/lib/commission/push.test.ts new file mode 100644 index 0000000..e81ad96 --- /dev/null +++ b/lib/commission/push.test.ts @@ -0,0 +1,15 @@ +import { describe, expect, it, vi } from "vitest"; + +vi.mock("server-only", () => ({})); +const { validPushEndpoint } = await import("./push"); + +describe("commission push endpoints", () => { + it("accepts browser push services and rejects arbitrary destinations", () => { + expect(validPushEndpoint("https://fcm.googleapis.com/fcm/send/token")).toBe(true); + expect(validPushEndpoint("https://updates.push.services.mozilla.com/wpush/v2/token")).toBe(true); + expect(validPushEndpoint("https://web.push.apple.com/token")).toBe(true); + expect(validPushEndpoint("https://127.0.0.1/push")).toBe(false); + expect(validPushEndpoint("https://fcm.googleapis.com.evil.test/push")).toBe(false); + expect(validPushEndpoint("http://fcm.googleapis.com/push")).toBe(false); + }); +}); diff --git a/lib/commission/push.ts b/lib/commission/push.ts new file mode 100644 index 0000000..a76fb91 --- /dev/null +++ b/lib/commission/push.ts @@ -0,0 +1,58 @@ +import "server-only"; + +import { and, eq, ne, or } from "drizzle-orm"; +import webPush from "web-push"; +import { getDb } from "@/db"; +import { commissionPushSubscriptions, users } from "@/db/schema"; + +export function pushPublicKey() { + return process.env.WEB_PUSH_PUBLIC_KEY && process.env.WEB_PUSH_PRIVATE_KEY && process.env.WEB_PUSH_SUBJECT + ? process.env.WEB_PUSH_PUBLIC_KEY : null; +} + +export function validPushEndpoint(value: string) { + try { + const url = new URL(value); + const host = url.hostname.toLowerCase(); + return url.protocol === "https:" && !url.username && !url.password && + (host === "fcm.googleapis.com" || host === "updates.push.services.mozilla.com" || + host === "web.push.apple.com" || host.endsWith(".push.apple.com") || + host.endsWith(".notify.windows.com")); + } catch { return false; } +} + +export async function sendCommissionMessagePush(message: { + id: string; ticketId: string; ticketTitle: string; customerId: string; authorId: string; + authorName: string; text: string | null; +}) { + if (!pushPublicKey()) return; + const subscriptions = await getDb().select({ subscription: commissionPushSubscriptions }) + .from(commissionPushSubscriptions) + .innerJoin(users, eq(users.id, commissionPushSubscriptions.userId)) + .where(and(ne(commissionPushSubscriptions.userId, message.authorId), eq(users.banned, false), + or(and(eq(commissionPushSubscriptions.scope, "customer"), + eq(commissionPushSubscriptions.userId, message.customerId)), + and(eq(commissionPushSubscriptions.scope, "admin"), eq(users.role, "admin"), + eq(users.emailVerified, true))))); + webPush.setVapidDetails(process.env.WEB_PUSH_SUBJECT!, process.env.WEB_PUSH_PUBLIC_KEY!, + process.env.WEB_PUSH_PRIVATE_KEY!); + for (let offset = 0; offset < subscriptions.length; offset += 10) { + await Promise.all(subscriptions.slice(offset, offset + 10).map(async ({ subscription }) => { + const payload = JSON.stringify({ + id: message.id, title: `${message.authorName} · ${message.ticketTitle}`, + body: message.text?.slice(0, 300) || "ส่งรูปภาพ", + url: `/${subscription.scope === "admin" ? "admin/commission" : "commission/tickets"}/${message.ticketId}`, + }); + try { + await webPush.sendNotification({ endpoint: subscription.endpoint, + keys: { p256dh: subscription.p256dh, auth: subscription.auth } }, payload, + { TTL: 60 * 60 * 24, timeout: 5000 }); + } catch (cause) { + if (cause && typeof cause === "object" && "statusCode" in cause && + (cause.statusCode === 404 || cause.statusCode === 410)) + await getDb().delete(commissionPushSubscriptions) + .where(eq(commissionPushSubscriptions.endpoint, subscription.endpoint)); + } + })); + } +} diff --git a/lib/commission/server.ts b/lib/commission/server.ts index b0bca47..a8b26f8 100644 --- a/lib/commission/server.ts +++ b/lib/commission/server.ts @@ -16,13 +16,13 @@ export async function requireCommissionUser() { return user; } -export async function notifyCommission(ticketId: string, userId: string) { +export async function notifyCommission(ticketId: string, userId: string, payload = "changed") { try { const client = await getRedisClient(); await Promise.all([ - client.publish(redisEventChannel(`commission:ticket:${ticketId}`), "changed"), - client.publish(redisEventChannel(`commission:user:${userId}`), "changed"), - client.publish(redisEventChannel("commission:admin"), "changed"), + client.publish(redisEventChannel(`commission:ticket:${ticketId}`), payload), + client.publish(redisEventChannel(`commission:user:${userId}`), payload), + client.publish(redisEventChannel("commission:admin"), payload), ]); } catch { // The database is authoritative; a reconnect or page refresh catches up. diff --git a/package.json b/package.json index ef450f2..39fa448 100644 --- a/package.json +++ b/package.json @@ -64,6 +64,7 @@ "sonner": "^2.0.8", "tailwind-merge": "^3.6.0", "tw-animate-css": "^1.4.0", + "web-push": "^3.6.7", "zod": "^4.4.3" }, "devDependencies": { @@ -74,6 +75,7 @@ "@types/react": "^19", "@types/react-dom": "^19", "@types/sanitize-html": "^2.16.1", + "@types/web-push": "^3.6.4", "@vitest/coverage-v8": "^4.1.11", "drizzle-kit": "0.31.11", "eslint": "^9", diff --git a/public/commission-push-sw.js b/public/commission-push-sw.js new file mode 100644 index 0000000..8d4549e --- /dev/null +++ b/public/commission-push-sw.js @@ -0,0 +1,22 @@ +self.addEventListener("push", (event) => { + if (!event.data) return; + const message = event.data.json(); + event.waitUntil(self.registration.showNotification(message.title, { + body: message.body, + icon: "/icon.png", + tag: message.id, + data: { url: message.url }, + })); +}); + +self.addEventListener("notificationclick", (event) => { + event.notification.close(); + const url = new URL(event.notification.data.url, self.location.origin); + if (url.origin !== self.location.origin) return; + event.waitUntil((async () => { + const windows = await self.clients.matchAll({ type: "window", includeUncontrolled: true }); + const existing = windows.find((client) => client.url === url.href); + if (existing) return existing.focus(); + return self.clients.openWindow(url.href); + })()); +});