Compare commits
No commits in common. "b64226cbd8dc13b9e255dd92d662c08782756b63" and "942a03d99aca3a47d5c32a63d16ed2585bcdfec0" have entirely different histories.
b64226cbd8
...
942a03d99a
36 changed files with 3885 additions and 2133 deletions
|
|
@ -1,6 +0,0 @@
|
||||||
-- Add subscription_status to families for payment-provider abstraction.
|
|
||||||
-- The actual payment integration (Razorpay TBD) will only need to flip
|
|
||||||
-- families.tier and set subscription_status; all quota/member enforcement
|
|
||||||
-- reads from these two fields via isPaidFamily() in src/lib/quota.ts.
|
|
||||||
ALTER TABLE families
|
|
||||||
ADD COLUMN IF NOT EXISTS subscription_status varchar(20) DEFAULT NULL;
|
|
||||||
|
|
@ -50,13 +50,6 @@
|
||||||
"when": 1748394000000,
|
"when": 1748394000000,
|
||||||
"tag": "0006_family_invites_missing_cols",
|
"tag": "0006_family_invites_missing_cols",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
},
|
|
||||||
{
|
|
||||||
"idx": 7,
|
|
||||||
"version": "7",
|
|
||||||
"when": 1748480400000,
|
|
||||||
"tag": "0007_subscription_status",
|
|
||||||
"breakpoints": true
|
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
@ -1,12 +1,4 @@
|
||||||
import type { NextConfig } from "next";
|
import type { NextConfig } from "next";
|
||||||
import withSerwistInit from "@serwist/next";
|
|
||||||
|
|
||||||
const withSerwist = withSerwistInit({
|
|
||||||
swSrc: "src/app/sw.ts",
|
|
||||||
swDest: "public/sw.js",
|
|
||||||
// Disable in dev so it never interferes with HMR / hot reload
|
|
||||||
disable: process.env.NODE_ENV === "development",
|
|
||||||
});
|
|
||||||
|
|
||||||
const nextConfig: NextConfig = {
|
const nextConfig: NextConfig = {
|
||||||
output: "standalone",
|
output: "standalone",
|
||||||
|
|
@ -34,4 +26,4 @@ const nextConfig: NextConfig = {
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
export default withSerwist(nextConfig);
|
export default nextConfig;
|
||||||
13
package.json
13
package.json
|
|
@ -4,22 +4,19 @@
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "next dev",
|
"dev": "next dev",
|
||||||
"build": "next build --webpack",
|
"build": "next build",
|
||||||
"start": "next start",
|
"start": "next start",
|
||||||
"db:generate": "drizzle-kit generate",
|
"db:generate": "drizzle-kit generate",
|
||||||
"db:migrate": "tsx src/db/migrate.ts",
|
"db:migrate": "tsx src/db/migrate.ts",
|
||||||
"db:studio": "drizzle-kit studio",
|
"db:studio": "drizzle-kit studio",
|
||||||
"db:pull": "drizzle-kit pull",
|
"db:pull": "drizzle-kit pull",
|
||||||
"db:build-migrator": "node scripts/build-migrator.mjs",
|
"db:build-migrator": "node scripts/build-migrator.mjs"
|
||||||
"test": "vitest run",
|
|
||||||
"test:watch": "vitest"
|
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@auth/drizzle-adapter": "^1.11.2",
|
"@auth/drizzle-adapter": "^1.11.2",
|
||||||
"@aws-sdk/client-s3": "^3.1045.0",
|
"@aws-sdk/client-s3": "^3.1045.0",
|
||||||
"@aws-sdk/s3-request-presigner": "^3.1045.0",
|
"@aws-sdk/s3-request-presigner": "^3.1045.0",
|
||||||
"@react-pdf/renderer": "^4.5.1",
|
"@react-pdf/renderer": "^4.5.1",
|
||||||
"@serwist/next": "9.5.11",
|
|
||||||
"arctic": "^3.7.0",
|
"arctic": "^3.7.0",
|
||||||
"bcryptjs": "^3.0.3",
|
"bcryptjs": "^3.0.3",
|
||||||
"chart.js": "^4.5.1",
|
"chart.js": "^4.5.1",
|
||||||
|
|
@ -29,6 +26,7 @@
|
||||||
"nanoid": "^5.1.11",
|
"nanoid": "^5.1.11",
|
||||||
"next": "16.2.6",
|
"next": "16.2.6",
|
||||||
"next-auth": "5.0.0-beta.31",
|
"next-auth": "5.0.0-beta.31",
|
||||||
|
"next-pwa": "^5.6.0",
|
||||||
"nodemailer": "^7.0.13",
|
"nodemailer": "^7.0.13",
|
||||||
"openai": "^6.37.0",
|
"openai": "^6.37.0",
|
||||||
"postgres": "^3.4.9",
|
"postgres": "^3.4.9",
|
||||||
|
|
@ -38,7 +36,6 @@
|
||||||
"react-dom": "19.2.4",
|
"react-dom": "19.2.4",
|
||||||
"recharts": "^3.8.1",
|
"recharts": "^3.8.1",
|
||||||
"resend": "^6.12.3",
|
"resend": "^6.12.3",
|
||||||
"serwist": "9.5.11",
|
|
||||||
"sharp": "^0.34.5",
|
"sharp": "^0.34.5",
|
||||||
"zod": "^4.4.3"
|
"zod": "^4.4.3"
|
||||||
},
|
},
|
||||||
|
|
@ -49,12 +46,10 @@
|
||||||
"@types/react": "^19",
|
"@types/react": "^19",
|
||||||
"@types/react-dom": "^19",
|
"@types/react-dom": "^19",
|
||||||
"@types/sharp": "^0.32.0",
|
"@types/sharp": "^0.32.0",
|
||||||
"@vitest/coverage-v8": "^4.1.7",
|
|
||||||
"drizzle-kit": "^0.31.10",
|
"drizzle-kit": "^0.31.10",
|
||||||
"esbuild": "^0.25.12",
|
"esbuild": "^0.25.12",
|
||||||
"tailwindcss": "^4",
|
"tailwindcss": "^4",
|
||||||
"tsx": "^4.21.0",
|
"tsx": "^4.21.0",
|
||||||
"typescript": "^5",
|
"typescript": "^5"
|
||||||
"vitest": "^4.1.7"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
4515
pnpm-lock.yaml
generated
4515
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load diff
Binary file not shown.
|
Before Width: | Height: | Size: 2.4 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 9.7 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 2.2 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 6.6 KiB |
21
public/manifest.json
Normal file
21
public/manifest.json
Normal file
|
|
@ -0,0 +1,21 @@
|
||||||
|
{
|
||||||
|
"name": "Tia - Baby Tracking",
|
||||||
|
"short_name": "Tia",
|
||||||
|
"description": "Your baby tracking companion",
|
||||||
|
"start_url": "/",
|
||||||
|
"display": "standalone",
|
||||||
|
"background_color": "#fdf2f2",
|
||||||
|
"theme_color": "#fb7185",
|
||||||
|
"icons": [
|
||||||
|
{
|
||||||
|
"src": "/icon-192.png",
|
||||||
|
"sizes": "192x192",
|
||||||
|
"type": "image/png"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"src": "/icon-512.png",
|
||||||
|
"sizes": "512x512",
|
||||||
|
"type": "image/png"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
51
public/sw.js
51
public/sw.js
File diff suppressed because one or more lines are too long
|
|
@ -1,47 +0,0 @@
|
||||||
// Generates PWA icon PNGs from an SVG template using sharp.
|
|
||||||
// Run: node scripts/generate-icons.mjs
|
|
||||||
import sharp from "sharp";
|
|
||||||
import { writeFileSync } from "fs";
|
|
||||||
import path from "path";
|
|
||||||
import { fileURLToPath } from "url";
|
|
||||||
|
|
||||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
||||||
const outDir = path.join(__dirname, "../public/icons");
|
|
||||||
|
|
||||||
// Brand colors from the app
|
|
||||||
const BG = "#fb7185"; // rose-400
|
|
||||||
|
|
||||||
// SVG template — rounded square with cherry blossom character.
|
|
||||||
// For maskable: full bleed background, content within safe zone (inner 80%).
|
|
||||||
function makeSvg(size, maskable = false) {
|
|
||||||
const radius = maskable ? 0 : Math.round(size * 0.18);
|
|
||||||
const fontSize = maskable ? Math.round(size * 0.48) : Math.round(size * 0.56);
|
|
||||||
const y = maskable ? Math.round(size * 0.68) : Math.round(size * 0.72);
|
|
||||||
return `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 ${size} ${size}">
|
|
||||||
<rect width="${size}" height="${size}" rx="${radius}" fill="${BG}"/>
|
|
||||||
<text
|
|
||||||
x="${size / 2}"
|
|
||||||
y="${y}"
|
|
||||||
font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif"
|
|
||||||
font-weight="700"
|
|
||||||
font-size="${fontSize}"
|
|
||||||
text-anchor="middle"
|
|
||||||
fill="white"
|
|
||||||
dominant-baseline="auto"
|
|
||||||
>T</text>
|
|
||||||
</svg>`;
|
|
||||||
}
|
|
||||||
|
|
||||||
const icons = [
|
|
||||||
{ name: "192.png", size: 192, maskable: false },
|
|
||||||
{ name: "512.png", size: 512, maskable: false },
|
|
||||||
{ name: "maskable-512.png", size: 512, maskable: true },
|
|
||||||
{ name: "apple-180.png", size: 180, maskable: false },
|
|
||||||
];
|
|
||||||
|
|
||||||
for (const icon of icons) {
|
|
||||||
const svg = Buffer.from(makeSvg(icon.size, icon.maskable));
|
|
||||||
const outPath = path.join(outDir, icon.name);
|
|
||||||
await sharp(svg).png().toFile(outPath);
|
|
||||||
console.log(`✓ ${icon.name}`);
|
|
||||||
}
|
|
||||||
|
|
@ -1,391 +0,0 @@
|
||||||
/**
|
|
||||||
* quota.test.ts — Unit tests for storage quota and member limit enforcement.
|
|
||||||
*
|
|
||||||
* Pure-function tests run without any DB. DB-bound function tests mock the
|
|
||||||
* @/db module so no real database connection is required.
|
|
||||||
*
|
|
||||||
* Run: pnpm test
|
|
||||||
*/
|
|
||||||
|
|
||||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
|
||||||
import {
|
|
||||||
isPaidFamily,
|
|
||||||
wouldExceedQuota,
|
|
||||||
isAtMemberLimit,
|
|
||||||
formatBytes,
|
|
||||||
FREE_STORAGE_LIMIT_BYTES,
|
|
||||||
FREE_MEMBER_LIMIT,
|
|
||||||
STORAGE_WARN_THRESHOLD,
|
|
||||||
} from "@/lib/quota";
|
|
||||||
|
|
||||||
// ─── Pure function tests (no DB, no mocks needed) ─────────────────────────────
|
|
||||||
|
|
||||||
describe("isPaidFamily", () => {
|
|
||||||
it("returns false for 'free'", () => {
|
|
||||||
expect(isPaidFamily("free")).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns false for null", () => {
|
|
||||||
expect(isPaidFamily(null)).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns false for undefined", () => {
|
|
||||||
expect(isPaidFamily(undefined)).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns true for 'pro'", () => {
|
|
||||||
expect(isPaidFamily("pro")).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns true for any non-free string", () => {
|
|
||||||
expect(isPaidFamily("paid")).toBe(true);
|
|
||||||
expect(isPaidFamily("enterprise")).toBe(true);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("wouldExceedQuota", () => {
|
|
||||||
const LIMIT = FREE_STORAGE_LIMIT_BYTES; // 1 GiB
|
|
||||||
|
|
||||||
it("allows upload when usage + declared <= limit", () => {
|
|
||||||
expect(wouldExceedQuota(900_000_000, 100_000_000, LIMIT)).toBe(false); // exactly 1 GiB
|
|
||||||
});
|
|
||||||
|
|
||||||
it("blocks upload when usage + declared > limit", () => {
|
|
||||||
expect(wouldExceedQuota(900_000_000, 200_000_000, LIMIT)).toBe(true); // over by 100 MB
|
|
||||||
});
|
|
||||||
|
|
||||||
it("blocks when already at limit with any positive declared size", () => {
|
|
||||||
expect(wouldExceedQuota(LIMIT, 1, LIMIT)).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("allows zero-byte declared upload when under limit", () => {
|
|
||||||
expect(wouldExceedQuota(500_000_000, 0, LIMIT)).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("blocks zero-byte declared upload when already over limit (post-downgrade)", () => {
|
|
||||||
// Family was on paid, accumulated > 1 GiB, then downgraded.
|
|
||||||
// Even a 0-byte declared should report over quota.
|
|
||||||
expect(wouldExceedQuota(LIMIT + 1, 0, LIMIT)).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("correctly handles large files within quota", () => {
|
|
||||||
// 950 MB used, 50 MB upload → 1000 MB total, under 1 GiB (1024 MB)
|
|
||||||
expect(wouldExceedQuota(950_000_000, 50_000_000, LIMIT)).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("correctly handles combined memories + attachments sum", () => {
|
|
||||||
// SUM from memories (600 MB) + attachments (200 MB) = 800 MB, + 300 MB upload → over
|
|
||||||
const memoriesBytes = 600_000_000;
|
|
||||||
const attachmentsBytes = 200_000_000;
|
|
||||||
const combined = memoriesBytes + attachmentsBytes;
|
|
||||||
expect(wouldExceedQuota(combined, 300_000_000, LIMIT)).toBe(true);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("isAtMemberLimit", () => {
|
|
||||||
it("blocks at limit on free tier", () => {
|
|
||||||
expect(isAtMemberLimit(2, FREE_MEMBER_LIMIT, false)).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("blocks above limit on free tier", () => {
|
|
||||||
expect(isAtMemberLimit(5, FREE_MEMBER_LIMIT, false)).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("allows below limit on free tier", () => {
|
|
||||||
expect(isAtMemberLimit(1, FREE_MEMBER_LIMIT, false)).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("always allows on paid tier regardless of count", () => {
|
|
||||||
expect(isAtMemberLimit(100, FREE_MEMBER_LIMIT, true)).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("freeze rule: paid → free downgrade with 4 members blocks new invites, not existing members", () => {
|
|
||||||
// After downgrade, all 4 members still exist (roles unchanged — enforced elsewhere).
|
|
||||||
// The limit check sees count=4, limit=2, paid=false → blocked for new invites.
|
|
||||||
expect(isAtMemberLimit(4, 2, false)).toBe(true);
|
|
||||||
// But if tier were still paid, it would be allowed:
|
|
||||||
expect(isAtMemberLimit(4, 2, true)).toBe(false);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("formatBytes", () => {
|
|
||||||
it("formats bytes", () => {
|
|
||||||
expect(formatBytes(512)).toBe("512 B");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("formats kilobytes", () => {
|
|
||||||
expect(formatBytes(1024)).toBe("1.0 KB");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("formats megabytes", () => {
|
|
||||||
expect(formatBytes(10 * 1024 * 1024)).toBe("10.0 MB");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("formats gigabytes", () => {
|
|
||||||
expect(formatBytes(1_073_741_824)).toBe("1.00 GB");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("formats 0 bytes", () => {
|
|
||||||
expect(formatBytes(0)).toBe("0 B");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("constants", () => {
|
|
||||||
it("FREE_STORAGE_LIMIT_BYTES is exactly 1 GiB", () => {
|
|
||||||
expect(FREE_STORAGE_LIMIT_BYTES).toBe(1_073_741_824);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("FREE_MEMBER_LIMIT is 2", () => {
|
|
||||||
expect(FREE_MEMBER_LIMIT).toBe(2);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("STORAGE_WARN_THRESHOLD is 0.8", () => {
|
|
||||||
expect(STORAGE_WARN_THRESHOLD).toBe(0.8);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// ─── DB-bound function tests (mocked DB) ──────────────────────────────────────
|
|
||||||
|
|
||||||
// We mock the @/db module so tests don't need a real Postgres connection.
|
|
||||||
vi.mock("@/db", () => ({
|
|
||||||
sql: vi.fn(),
|
|
||||||
}));
|
|
||||||
|
|
||||||
import { sql } from "@/db";
|
|
||||||
import {
|
|
||||||
getFamilyStorageUsage,
|
|
||||||
checkStorageQuota,
|
|
||||||
checkMemberLimit,
|
|
||||||
getStorageInfo,
|
|
||||||
} from "@/lib/quota";
|
|
||||||
|
|
||||||
const mockSql = sql as unknown as ReturnType<typeof vi.fn>;
|
|
||||||
|
|
||||||
// Helper: make sql return specific results for tagged template literals.
|
|
||||||
// The postgres.js `sql` is a tagged template function, not a regular function,
|
|
||||||
// but vi.fn() captures the call regardless.
|
|
||||||
function sqlReturns(...results: unknown[][]) {
|
|
||||||
let callIndex = 0;
|
|
||||||
mockSql.mockImplementation((..._args: unknown[]) => {
|
|
||||||
return Promise.resolve(results[callIndex++ % results.length]);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
vi.clearAllMocks();
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("getFamilyStorageUsage", () => {
|
|
||||||
it("sums memories and attachments correctly", async () => {
|
|
||||||
// memories: 600 MB, attachments: 200 MB → 800 MB total
|
|
||||||
sqlReturns(
|
|
||||||
[{ bytes: "629145600" }], // memories: 600 MB
|
|
||||||
[{ bytes: "209715200" }] // attachments: 200 MB
|
|
||||||
);
|
|
||||||
const usage = await getFamilyStorageUsage("family-a");
|
|
||||||
expect(usage).toBe(629145600 + 209715200);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns 0 when both tables are empty", async () => {
|
|
||||||
sqlReturns([{ bytes: "0" }], [{ bytes: "0" }]);
|
|
||||||
expect(await getFamilyStorageUsage("family-empty")).toBe(0);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("tenant isolation: queried with the correct familyId", async () => {
|
|
||||||
sqlReturns([{ bytes: "0" }], [{ bytes: "0" }]);
|
|
||||||
await getFamilyStorageUsage("family-a");
|
|
||||||
// Both SQL calls should have received family-a in their args
|
|
||||||
const calls = mockSql.mock.calls;
|
|
||||||
expect(calls).toHaveLength(2);
|
|
||||||
// The familyId is passed as a tagged template argument; verify it appears
|
|
||||||
const allArgs = calls.flatMap((c: unknown[]) => c);
|
|
||||||
expect(allArgs).toContain("family-a");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("excludes uploading-status memories (counted by WHERE clause in SQL)", async () => {
|
|
||||||
// The WHERE processing_status != 'uploading' is in the SQL template.
|
|
||||||
// Here we verify the SUM result reflects only confirmed uploads.
|
|
||||||
// Simulate: one confirmed memory (100 MB), pending stays excluded via SQL
|
|
||||||
sqlReturns([{ bytes: "104857600" }], [{ bytes: "0" }]);
|
|
||||||
const usage = await getFamilyStorageUsage("family-b");
|
|
||||||
expect(usage).toBe(104857600);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("checkStorageQuota", () => {
|
|
||||||
it("allows upload when family is under quota", async () => {
|
|
||||||
// family: free tier, 500 MB used
|
|
||||||
sqlReturns(
|
|
||||||
[{ tier: "free" }], // families query
|
|
||||||
[{ bytes: "524288000" }], // memories SUM (500 MB)
|
|
||||||
[{ bytes: "0" }] // attachments SUM
|
|
||||||
);
|
|
||||||
const result = await checkStorageQuota("family-a", 100 * 1024 * 1024); // +100 MB
|
|
||||||
expect(result.allowed).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("blocks upload when declared size would push over quota", async () => {
|
|
||||||
// family: free tier, 950 MB used; trying to upload 200 MB → would be 1150 MB > 1 GiB
|
|
||||||
sqlReturns(
|
|
||||||
[{ tier: "free" }],
|
|
||||||
[{ bytes: "996147200" }], // 950 MB
|
|
||||||
[{ bytes: "0" }]
|
|
||||||
);
|
|
||||||
const result = await checkStorageQuota("family-a", 200 * 1024 * 1024); // 200 MB
|
|
||||||
expect(result.allowed).toBe(false);
|
|
||||||
if (!result.allowed) {
|
|
||||||
expect(result.reason).toBe("storage_quota_exceeded");
|
|
||||||
expect(result.usedBytes).toBe(996147200);
|
|
||||||
expect(result.limitBytes).toBe(FREE_STORAGE_LIMIT_BYTES);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
it("blocks upload when family is already over quota (post-downgrade)", async () => {
|
|
||||||
// Paid family accumulated 2 GB, then downgraded to free.
|
|
||||||
// Even a tiny upload (1 byte) should be blocked.
|
|
||||||
sqlReturns(
|
|
||||||
[{ tier: "free" }],
|
|
||||||
[{ bytes: "2147483648" }], // 2 GB in memories
|
|
||||||
[{ bytes: "0" }]
|
|
||||||
);
|
|
||||||
const result = await checkStorageQuota("family-a", 1);
|
|
||||||
expect(result.allowed).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("allows upload for paid family regardless of usage", async () => {
|
|
||||||
sqlReturns(
|
|
||||||
[{ tier: "pro" }],
|
|
||||||
[{ bytes: "10737418240" }], // 10 GB (way over free limit)
|
|
||||||
[{ bytes: "0" }]
|
|
||||||
);
|
|
||||||
const result = await checkStorageQuota("family-paid", 500 * 1024 * 1024);
|
|
||||||
expect(result.allowed).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("blocks upload when declared=0 but family is over quota", async () => {
|
|
||||||
sqlReturns(
|
|
||||||
[{ tier: "free" }],
|
|
||||||
[{ bytes: `${FREE_STORAGE_LIMIT_BYTES + 1}` }],
|
|
||||||
[{ bytes: "0" }]
|
|
||||||
);
|
|
||||||
const result = await checkStorageQuota("family-a", 0);
|
|
||||||
expect(result.allowed).toBe(false);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("checkMemberLimit", () => {
|
|
||||||
it("allows invite when count < limit on free tier", async () => {
|
|
||||||
sqlReturns([{ count: "1", max_members: 2, tier: "free" }]);
|
|
||||||
const result = await checkMemberLimit("family-a");
|
|
||||||
expect(result.allowed).toBe(true);
|
|
||||||
if (result.allowed) expect(result.currentCount).toBe(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("blocks invite when count = limit on free tier", async () => {
|
|
||||||
sqlReturns([{ count: "2", max_members: 2, tier: "free" }]);
|
|
||||||
const result = await checkMemberLimit("family-a");
|
|
||||||
expect(result.allowed).toBe(false);
|
|
||||||
if (!result.allowed) {
|
|
||||||
expect(result.reason).toBe("member_limit_reached");
|
|
||||||
expect(result.currentCount).toBe(2);
|
|
||||||
expect(result.limit).toBe(2);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
it("blocks invite when count > limit (post-downgrade freeze)", async () => {
|
|
||||||
// 4 members from paid tier, now free — new invites blocked, existing retained
|
|
||||||
sqlReturns([{ count: "4", max_members: 2, tier: "free" }]);
|
|
||||||
const result = await checkMemberLimit("family-downgraded");
|
|
||||||
expect(result.allowed).toBe(false);
|
|
||||||
if (!result.allowed) {
|
|
||||||
expect(result.currentCount).toBe(4);
|
|
||||||
expect(result.limit).toBe(2);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
it("allows invite on paid tier regardless of count", async () => {
|
|
||||||
sqlReturns([{ count: "50", max_members: 2, tier: "pro" }]);
|
|
||||||
const result = await checkMemberLimit("family-paid");
|
|
||||||
expect(result.allowed).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("respects custom max_members from DB (configurable per family)", async () => {
|
|
||||||
// Admin could set max_members=5 for a special promo plan
|
|
||||||
sqlReturns([{ count: "4", max_members: 5, tier: "free" }]);
|
|
||||||
const result = await checkMemberLimit("family-promo");
|
|
||||||
expect(result.allowed).toBe(true);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("getStorageInfo", () => {
|
|
||||||
it("returns approaching=true near 80% usage", async () => {
|
|
||||||
const nearLimit = Math.floor(FREE_STORAGE_LIMIT_BYTES * 0.85);
|
|
||||||
sqlReturns(
|
|
||||||
[{ tier: "free" }],
|
|
||||||
[{ bytes: String(nearLimit) }],
|
|
||||||
[{ bytes: "0" }]
|
|
||||||
);
|
|
||||||
const info = await getStorageInfo("family-a");
|
|
||||||
expect(info.approaching).toBe(true);
|
|
||||||
expect(info.exceeded).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns exceeded=true at 100%+ usage", async () => {
|
|
||||||
sqlReturns(
|
|
||||||
[{ tier: "free" }],
|
|
||||||
[{ bytes: String(FREE_STORAGE_LIMIT_BYTES + 1000) }],
|
|
||||||
[{ bytes: "0" }]
|
|
||||||
);
|
|
||||||
const info = await getStorageInfo("family-a");
|
|
||||||
expect(info.exceeded).toBe(true);
|
|
||||||
expect(info.approaching).toBe(false); // exceeded takes over
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns approaching=false and exceeded=false for paid family", async () => {
|
|
||||||
sqlReturns(
|
|
||||||
[{ tier: "pro" }],
|
|
||||||
[{ bytes: String(FREE_STORAGE_LIMIT_BYTES * 10) }],
|
|
||||||
[{ bytes: "0" }]
|
|
||||||
);
|
|
||||||
const info = await getStorageInfo("family-paid");
|
|
||||||
expect(info.approaching).toBe(false);
|
|
||||||
expect(info.exceeded).toBe(false);
|
|
||||||
expect(info.isPaid).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("over-quota family can still derive usage (read path unblocked)", async () => {
|
|
||||||
// getStorageInfo is the read path for the UI meter — must work even over quota.
|
|
||||||
sqlReturns(
|
|
||||||
[{ tier: "free" }],
|
|
||||||
[{ bytes: "2000000000" }],
|
|
||||||
[{ bytes: "0" }]
|
|
||||||
);
|
|
||||||
const info = await getStorageInfo("family-over");
|
|
||||||
expect(info.usedBytes).toBe(2_000_000_000);
|
|
||||||
expect(info.exceeded).toBe(true);
|
|
||||||
// The read itself succeeds — memories can still be read (enforced at route level)
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// ─── RLS / tenant isolation ────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
describe("tenant isolation", () => {
|
|
||||||
it("does not mix usage across families", async () => {
|
|
||||||
// Family A: 900 MB; Family B: 100 MB. Each call should see only its own usage.
|
|
||||||
const familyAUsage = 943718400; // 900 MB
|
|
||||||
const familyBUsage = 104857600; // 100 MB
|
|
||||||
|
|
||||||
mockSql
|
|
||||||
.mockImplementationOnce(() => Promise.resolve([{ bytes: String(familyAUsage) }]))
|
|
||||||
.mockImplementationOnce(() => Promise.resolve([{ bytes: "0" }]))
|
|
||||||
.mockImplementationOnce(() => Promise.resolve([{ bytes: String(familyBUsage) }]))
|
|
||||||
.mockImplementationOnce(() => Promise.resolve([{ bytes: "0" }]));
|
|
||||||
|
|
||||||
const usageA = await getFamilyStorageUsage("family-a");
|
|
||||||
const usageB = await getFamilyStorageUsage("family-b");
|
|
||||||
|
|
||||||
expect(usageA).toBe(familyAUsage);
|
|
||||||
expect(usageB).toBe(familyBUsage);
|
|
||||||
expect(usageA).not.toBe(usageB);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -2,7 +2,6 @@ import { ThemeProvider } from "@/app/ThemeProvider";
|
||||||
import { FamilyProvider } from "@/app/FamilyProvider";
|
import { FamilyProvider } from "@/app/FamilyProvider";
|
||||||
import { PageTransition } from "@/components/PageTransition";
|
import { PageTransition } from "@/components/PageTransition";
|
||||||
import { BottomNav } from "@/components/BottomNav";
|
import { BottomNav } from "@/components/BottomNav";
|
||||||
import { InstallPrompt } from "@/components/InstallPrompt";
|
|
||||||
|
|
||||||
export default function AppLayout({
|
export default function AppLayout({
|
||||||
children,
|
children,
|
||||||
|
|
@ -14,7 +13,6 @@ export default function AppLayout({
|
||||||
<FamilyProvider>
|
<FamilyProvider>
|
||||||
<PageTransition>{children}</PageTransition>
|
<PageTransition>{children}</PageTransition>
|
||||||
<BottomNav />
|
<BottomNav />
|
||||||
<InstallPrompt />
|
|
||||||
</FamilyProvider>
|
</FamilyProvider>
|
||||||
</ThemeProvider>
|
</ThemeProvider>
|
||||||
);
|
);
|
||||||
|
|
|
||||||
|
|
@ -4,8 +4,6 @@ import { useState, useEffect, useRef, useCallback } from "react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { useFamily } from "@/app/FamilyProvider";
|
import { useFamily } from "@/app/FamilyProvider";
|
||||||
import { Button, ConfirmDialog, Modal } from "@/components/ui";
|
import { Button, ConfirmDialog, Modal } from "@/components/ui";
|
||||||
import { StorageMeter, StorageQuotaBanner } from "@/components/StorageMeter";
|
|
||||||
import { formatBytes } from "@/lib/format-bytes";
|
|
||||||
|
|
||||||
const PRESET_FOLDERS = [
|
const PRESET_FOLDERS = [
|
||||||
{ id: "", label: "All", emoji: "🌟" },
|
{ id: "", label: "All", emoji: "🌟" },
|
||||||
|
|
@ -61,10 +59,6 @@ export default function MemoriesPage() {
|
||||||
const [newFolderName, setNewFolderName] = useState("");
|
const [newFolderName, setNewFolderName] = useState("");
|
||||||
const [newFolderEmoji, setNewFolderEmoji] = useState("📁");
|
const [newFolderEmoji, setNewFolderEmoji] = useState("📁");
|
||||||
|
|
||||||
// Quota state — fetched on mount, refreshed after any 402 response
|
|
||||||
const [quotaExceeded, setQuotaExceeded] = useState(false);
|
|
||||||
const [quotaBanner, setQuotaBanner] = useState<{ usedBytes: number; limitBytes: number } | null>(null);
|
|
||||||
|
|
||||||
const fileRef = useRef<HTMLInputElement>(null);
|
const fileRef = useRef<HTMLInputElement>(null);
|
||||||
const loaderRef = useRef<HTMLDivElement>(null);
|
const loaderRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
|
@ -75,20 +69,6 @@ export default function MemoriesPage() {
|
||||||
} catch {}
|
} catch {}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// Fetch storage quota on mount so we can disable the FAB before the user
|
|
||||||
// tries to upload and hits a 402 (better UX than a failed upload).
|
|
||||||
useEffect(() => {
|
|
||||||
fetch("/api/storage-usage")
|
|
||||||
.then(r => r.json())
|
|
||||||
.then(d => {
|
|
||||||
if (d.exceeded) {
|
|
||||||
setQuotaExceeded(true);
|
|
||||||
setQuotaBanner({ usedBytes: d.usedBytes, limitBytes: d.limitBytes });
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.catch(() => {});
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const allFolders: Folder[] = [...PRESET_FOLDERS, ...customFolders];
|
const allFolders: Folder[] = [...PRESET_FOLDERS, ...customFolders];
|
||||||
|
|
||||||
const handleCreateFolder = () => {
|
const handleCreateFolder = () => {
|
||||||
|
|
@ -145,37 +125,23 @@ export default function MemoriesPage() {
|
||||||
if (!file || !childId) return;
|
if (!file || !childId) return;
|
||||||
setUploading(true);
|
setUploading(true);
|
||||||
try {
|
try {
|
||||||
// Step 1: Get presigned URL (quota gate runs here server-side)
|
|
||||||
const initRes = await fetch("/api/upload", {
|
const initRes = await fetch("/api/upload", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ filename: file.name, contentType: file.type, childId, sizeBytes: file.size }),
|
body: JSON.stringify({ filename: file.name, contentType: file.type, childId, sizeBytes: file.size }),
|
||||||
});
|
});
|
||||||
const initData = await initRes.json();
|
const { key, memoryId, publicUrl, error } = await initRes.json();
|
||||||
|
if (error) { alert("Error: " + error); return; }
|
||||||
|
|
||||||
if (!initRes.ok) {
|
|
||||||
if (initRes.status === 402 && initData.reason === "storage_quota_exceeded") {
|
|
||||||
setQuotaExceeded(true);
|
|
||||||
setQuotaBanner({ usedBytes: initData.usedBytes, limitBytes: initData.limitBytes });
|
|
||||||
} else {
|
|
||||||
alert("Error: " + (initData.error ?? "Upload failed"));
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const { key, memoryId, publicUrl } = initData;
|
|
||||||
|
|
||||||
// Step 2: Upload file to R2 via proxy
|
|
||||||
const putParams = new URLSearchParams({ key, contentType: file.type });
|
const putParams = new URLSearchParams({ key, contentType: file.type });
|
||||||
const putRes = await fetch(`/api/upload?${putParams}`, {
|
const putRes = await fetch(`/api/upload?${putParams}`, {
|
||||||
method: "PUT", body: file, headers: { "Content-Type": file.type },
|
method: "PUT", body: file, headers: { "Content-Type": file.type },
|
||||||
});
|
});
|
||||||
if (!putRes.ok) {
|
if (!putRes.ok) {
|
||||||
const putErr = await putRes.json().catch(() => ({})) as { error?: string };
|
const e = await putRes.json().catch(() => ({})) as { error?: string };
|
||||||
throw new Error(putErr.error ?? `Upload failed (${putRes.status})`);
|
throw new Error(e.error ?? `Upload failed (${putRes.status})`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Step 3: Assign folder if chosen
|
|
||||||
if (pendingFolder) {
|
if (pendingFolder) {
|
||||||
await fetch(`/api/memories/${memoryId}`, {
|
await fetch(`/api/memories/${memoryId}`, {
|
||||||
method: "PATCH",
|
method: "PATCH",
|
||||||
|
|
@ -184,20 +150,8 @@ export default function MemoriesPage() {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Step 4: Confirm — server reconciles actual R2 size against quota
|
await fetch(`/api/memories/${memoryId}/confirm`, { method: "POST" });
|
||||||
const confirmRes = await fetch(`/api/memories/${memoryId}/confirm`, { method: "POST" });
|
|
||||||
if (!confirmRes.ok && confirmRes.status === 402) {
|
|
||||||
// Actual file size exceeded quota; server deleted the R2 object and
|
|
||||||
// marked the row failed. Refresh quota state and skip optimistic update.
|
|
||||||
setQuotaExceeded(true);
|
|
||||||
fetch("/api/storage-usage")
|
|
||||||
.then(r => r.json())
|
|
||||||
.then(d => setQuotaBanner({ usedBytes: d.usedBytes, limitBytes: d.limitBytes }))
|
|
||||||
.catch(() => {});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Step 5: Optimistic update in UI
|
|
||||||
const optimistic: Memory = {
|
const optimistic: Memory = {
|
||||||
id: memoryId, key, url: publicUrl, thumbnailUrl: null,
|
id: memoryId, key, url: publicUrl, thumbnailUrl: null,
|
||||||
sizeBytes: file.size, mimeType: file.type, title: null,
|
sizeBytes: file.size, mimeType: file.type, title: null,
|
||||||
|
|
@ -206,13 +160,10 @@ export default function MemoriesPage() {
|
||||||
processingStatus: "processing", createdAt: new Date().toISOString(),
|
processingStatus: "processing", createdAt: new Date().toISOString(),
|
||||||
};
|
};
|
||||||
setMemories(prev => [optimistic, ...prev]);
|
setMemories(prev => [optimistic, ...prev]);
|
||||||
} catch (err) {
|
} catch (err) { alert("Upload failed: " + err); }
|
||||||
alert("Upload failed: " + err);
|
|
||||||
} finally {
|
|
||||||
setUploading(false);
|
setUploading(false);
|
||||||
setPendingFolder("");
|
setPendingFolder("");
|
||||||
if (fileRef.current) fileRef.current.value = "";
|
if (fileRef.current) fileRef.current.value = "";
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleDelete = async (id: string) => {
|
const handleDelete = async (id: string) => {
|
||||||
|
|
@ -252,28 +203,12 @@ export default function MemoriesPage() {
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-gray-50 dark:bg-gray-900">
|
<div className="min-h-screen bg-gray-50 dark:bg-gray-900">
|
||||||
{/* Header */}
|
{/* Header */}
|
||||||
<div className="sticky top-0 z-10 bg-white dark:bg-gray-900 border-b border-gray-100 dark:border-gray-800 px-4 py-3 space-y-2">
|
<div className="sticky top-0 z-10 bg-white dark:bg-gray-900 border-b border-gray-100 dark:border-gray-800 px-4 py-3 flex items-center justify-between">
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<Link href="/menu" className="text-gray-500 dark:text-gray-400 p-1">←</Link>
|
<Link href="/menu" className="text-gray-500 dark:text-gray-400 p-1">←</Link>
|
||||||
<h1 className="text-xs font-semibold dark:text-white">Memories 📸</h1>
|
<h1 className="text-xs font-semibold dark:text-white">Memories 📸</h1>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{/* Storage meter — only visible when approaching or exceeded */}
|
|
||||||
<StorageMeter compact className="px-1" />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Storage quota banner — shown when upload is blocked */}
|
|
||||||
{quotaBanner && (
|
|
||||||
<div className="px-4 pt-3">
|
|
||||||
<StorageQuotaBanner
|
|
||||||
usedBytes={quotaBanner.usedBytes}
|
|
||||||
limitBytes={quotaBanner.limitBytes}
|
|
||||||
usedFormatted={formatBytes(quotaBanner.usedBytes)}
|
|
||||||
limitFormatted={formatBytes(quotaBanner.limitBytes)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Search */}
|
{/* Search */}
|
||||||
<form onSubmit={handleSearch} className="px-4 pt-3 pb-1 flex gap-2">
|
<form onSubmit={handleSearch} className="px-4 pt-3 pb-1 flex gap-2">
|
||||||
|
|
@ -351,19 +286,18 @@ export default function MemoriesPage() {
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Upload FAB — disabled when storage quota is exceeded */}
|
{/* Upload FAB */}
|
||||||
<div className="fixed bottom-6 right-6 z-20">
|
<div className="fixed bottom-6 right-6 z-20">
|
||||||
<button
|
<button
|
||||||
onClick={quotaExceeded ? undefined : handleUploadClick}
|
onClick={handleUploadClick}
|
||||||
disabled={uploading || quotaExceeded}
|
disabled={uploading}
|
||||||
title={quotaExceeded ? "Storage full — delete some memories or upgrade to upload more" : undefined}
|
|
||||||
className={`w-14 h-14 rounded-full shadow-xl flex items-center justify-center text-white text-2xl font-light transition-colors ${
|
className={`w-14 h-14 rounded-full shadow-xl flex items-center justify-center text-white text-2xl font-light transition-colors ${
|
||||||
uploading || quotaExceeded ? "bg-gray-400 cursor-not-allowed" : "bg-rose-400 hover:bg-rose-500 active:bg-rose-600"
|
uploading ? "bg-gray-400" : "bg-rose-400 hover:bg-rose-500 active:bg-rose-600"
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
{uploading ? "…" : quotaExceeded ? "⊘" : "+"}
|
{uploading ? "…" : "+"}
|
||||||
</button>
|
</button>
|
||||||
<input ref={fileRef} type="file" accept="image/*" onChange={handleUpload} className="hidden" disabled={uploading || quotaExceeded} />
|
<input ref={fileRef} type="file" accept="image/*" onChange={handleUpload} className="hidden" disabled={uploading} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Folder picker modal */}
|
{/* Folder picker modal */}
|
||||||
|
|
|
||||||
|
|
@ -25,12 +25,6 @@ export default function MenuPage() {
|
||||||
setSigningOut(true);
|
setSigningOut(true);
|
||||||
try {
|
try {
|
||||||
await fetch("/api/auth/signout", { method: "POST" });
|
await fetch("/api/auth/signout", { method: "POST" });
|
||||||
// Purge SW caches so a shared device can't see the previous user's
|
|
||||||
// cached baby photos or shell state after login.
|
|
||||||
if ("caches" in window) {
|
|
||||||
const keys = await caches.keys();
|
|
||||||
await Promise.all(keys.map((k) => caches.delete(k)));
|
|
||||||
}
|
|
||||||
router.push("/login");
|
router.push("/login");
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("Sign out failed:", err);
|
console.error("Sign out failed:", err);
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,6 @@ import { useRouter } from "next/navigation";
|
||||||
import { useTheme } from "@/app/ThemeProvider";
|
import { useTheme } from "@/app/ThemeProvider";
|
||||||
import { useFamily } from "@/app/FamilyProvider";
|
import { useFamily } from "@/app/FamilyProvider";
|
||||||
import { Button, Card, Input, Select, Badge } from "@/components/ui";
|
import { Button, Card, Input, Select, Badge } from "@/components/ui";
|
||||||
import { StorageMeter, MemberLimitBanner } from "@/components/StorageMeter";
|
|
||||||
|
|
||||||
interface Member {
|
interface Member {
|
||||||
id: string;
|
id: string;
|
||||||
|
|
@ -41,7 +40,7 @@ export default function SettingsPage() {
|
||||||
const [pedPhone, setPedPhone] = useState("");
|
const [pedPhone, setPedPhone] = useState("");
|
||||||
const [pedSaving, setPedSaving] = useState(false);
|
const [pedSaving, setPedSaving] = useState(false);
|
||||||
|
|
||||||
// Check if can invite more members (client-side pre-check; server enforces)
|
// Check if can invite more members
|
||||||
const canInvite = tier === "pro" || memberCount < 2;
|
const canInvite = tier === "pro" || memberCount < 2;
|
||||||
|
|
||||||
// Family name from provider or fallback
|
// Family name from provider or fallback
|
||||||
|
|
@ -151,9 +150,6 @@ export default function SettingsPage() {
|
||||||
if (data.success) {
|
if (data.success) {
|
||||||
setInviteEmail("");
|
setInviteEmail("");
|
||||||
fetchInvites();
|
fetchInvites();
|
||||||
} else if (data.reason === "member_limit_reached") {
|
|
||||||
// Trigger re-render of the limit banner with fresh data
|
|
||||||
fetchMembers();
|
|
||||||
} else {
|
} else {
|
||||||
alert(data.error);
|
alert(data.error);
|
||||||
}
|
}
|
||||||
|
|
@ -247,12 +243,6 @@ export default function SettingsPage() {
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Storage usage meter */}
|
|
||||||
<div>
|
|
||||||
<div className="text-sm font-medium text-gray-500 mb-2">Storage</div>
|
|
||||||
<StorageMeter />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Manage Children */}
|
{/* Manage Children */}
|
||||||
<Link href="/family" className="flex items-center justify-between p-3 border border-dashed border-gray-300 dark:border-gray-600 rounded-lg">
|
<Link href="/family" className="flex items-center justify-between p-3 border border-dashed border-gray-300 dark:border-gray-600 rounded-lg">
|
||||||
<span className="text-sm">Manage Children</span>
|
<span className="text-sm">Manage Children</span>
|
||||||
|
|
@ -280,10 +270,10 @@ export default function SettingsPage() {
|
||||||
|
|
||||||
{inviteOpen && (
|
{inviteOpen && (
|
||||||
<div className="px-4 pb-4">
|
<div className="px-4 pb-4">
|
||||||
{/* Member limit banner */}
|
{/* Pro upgrade prompt */}
|
||||||
{tier === "free" && !canInvite && (
|
{tier === "free" && !canInvite && (
|
||||||
<div className="mb-3">
|
<div className="p-3 bg-rose-50 rounded-lg mb-3">
|
||||||
<MemberLimitBanner currentCount={memberCount} limit={2} />
|
<p className="text-sm text-rose-600">Upgrade to Pro for unlimited family members</p>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -33,8 +33,6 @@ export async function POST(req: Request) {
|
||||||
// family_invites missing columns (0006)
|
// family_invites missing columns (0006)
|
||||||
`ALTER TABLE family_invites ADD COLUMN IF NOT EXISTS display_name text`,
|
`ALTER TABLE family_invites ADD COLUMN IF NOT EXISTS display_name text`,
|
||||||
`ALTER TABLE family_invites ADD COLUMN IF NOT EXISTS accepted_at timestamp`,
|
`ALTER TABLE family_invites ADD COLUMN IF NOT EXISTS accepted_at timestamp`,
|
||||||
// subscription_status on families (0007) — payment-provider abstraction
|
|
||||||
`ALTER TABLE families ADD COLUMN IF NOT EXISTS subscription_status varchar(20) DEFAULT NULL`,
|
|
||||||
// circles tables (0003)
|
// circles tables (0003)
|
||||||
`CREATE TABLE IF NOT EXISTS circles (id uuid PRIMARY KEY DEFAULT gen_random_uuid(), name text NOT NULL, created_by uuid NOT NULL REFERENCES families(id), created_at timestamptz NOT NULL DEFAULT now())`,
|
`CREATE TABLE IF NOT EXISTS circles (id uuid PRIMARY KEY DEFAULT gen_random_uuid(), name text NOT NULL, created_by uuid NOT NULL REFERENCES families(id), created_at timestamptz NOT NULL DEFAULT now())`,
|
||||||
`CREATE TABLE IF NOT EXISTS circle_members (circle_id uuid NOT NULL REFERENCES circles(id) ON DELETE CASCADE, family_id uuid NOT NULL REFERENCES families(id), role text NOT NULL DEFAULT 'member', joined_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (circle_id, family_id))`,
|
`CREATE TABLE IF NOT EXISTS circle_members (circle_id uuid NOT NULL REFERENCES circles(id) ON DELETE CASCADE, family_id uuid NOT NULL REFERENCES families(id), role text NOT NULL DEFAULT 'member', joined_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (circle_id, family_id))`,
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,6 @@ import { sql } from "@/db";
|
||||||
import { requireFamily } from "@/lib/auth";
|
import { requireFamily } from "@/lib/auth";
|
||||||
import { randomBytes } from "crypto";
|
import { randomBytes } from "crypto";
|
||||||
import { sendFamilyInviteEmail } from "@/lib/email";
|
import { sendFamilyInviteEmail } from "@/lib/email";
|
||||||
import { checkMemberLimit } from "@/lib/quota";
|
|
||||||
|
|
||||||
// GET - list invites for a family
|
// GET - list invites for a family
|
||||||
export async function GET(request: Request) {
|
export async function GET(request: Request) {
|
||||||
|
|
@ -38,20 +37,21 @@ export async function POST(request: Request) {
|
||||||
return NextResponse.json({ error: "email required" }, { status: 400 });
|
return NextResponse.json({ error: "email required" }, { status: 400 });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Member limit gate — COUNT(family_members) is source of truth.
|
// Check member count limit
|
||||||
// Freeze rule: paid → free downgrade leaves existing members intact;
|
const memberCheck = await sql.unsafe(
|
||||||
// only new invites are blocked until family is under limit or upgrades.
|
`SELECT f.max_members, f.tier, COUNT(fm.id) as member_count
|
||||||
const limitCheck = await checkMemberLimit(auth.session!.familyId!);
|
FROM families f
|
||||||
if (!limitCheck.allowed) {
|
LEFT JOIN family_members fm ON fm.family_id = f.id
|
||||||
return NextResponse.json(
|
WHERE f.id = $1
|
||||||
{
|
GROUP BY f.id`,
|
||||||
error: limitCheck.message,
|
[auth.session!.familyId]
|
||||||
reason: limitCheck.reason,
|
|
||||||
currentCount: limitCheck.currentCount,
|
|
||||||
limit: limitCheck.limit,
|
|
||||||
},
|
|
||||||
{ status: 403 }
|
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const family = memberCheck[0];
|
||||||
|
const canAdd = family.tier === "pro" || (family.member_count || 0) < (family.max_members || 2);
|
||||||
|
|
||||||
|
if (!canAdd) {
|
||||||
|
return NextResponse.json({ error: "Upgrade to Pro to add more members" }, { status: 403 });
|
||||||
}
|
}
|
||||||
|
|
||||||
const token = randomBytes(32).toString("hex");
|
const token = randomBytes(32).toString("hex");
|
||||||
|
|
|
||||||
|
|
@ -3,19 +3,6 @@ import { requireFamily } from "@/lib/auth";
|
||||||
import { sql } from "@/db";
|
import { sql } from "@/db";
|
||||||
import { generateThumbnail } from "@/lib/media/thumbnail";
|
import { generateThumbnail } from "@/lib/media/thumbnail";
|
||||||
import { processMemoryVision } from "@/lib/ai/vision";
|
import { processMemoryVision } from "@/lib/ai/vision";
|
||||||
import { S3Client, HeadObjectCommand, DeleteObjectCommand } from "@aws-sdk/client-s3";
|
|
||||||
import { reconcileActualSize } from "@/lib/quota";
|
|
||||||
|
|
||||||
function makeR2Client() {
|
|
||||||
const accountId = process.env.R2_ACCOUNT_ID!;
|
|
||||||
const accessKeyId = process.env.R2_ACCESS_KEY_ID!;
|
|
||||||
const secretAccessKey = process.env.R2_SECRET_ACCESS_KEY!;
|
|
||||||
return new S3Client({
|
|
||||||
region: "auto",
|
|
||||||
endpoint: `https://${accountId}.r2.cloudflarestorage.com`,
|
|
||||||
credentials: { accessKeyId, secretAccessKey },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// POST /api/memories/[id]/confirm — called after client finishes uploading to R2
|
// POST /api/memories/[id]/confirm — called after client finishes uploading to R2
|
||||||
export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
|
|
@ -25,71 +12,16 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ id:
|
||||||
|
|
||||||
const familyId = auth.session!.familyId!;
|
const familyId = auth.session!.familyId!;
|
||||||
|
|
||||||
const rows = await sql`
|
const rows = await sql`SELECT id, processing_status FROM memories WHERE id = ${id} AND family_id = ${familyId} LIMIT 1`;
|
||||||
SELECT id, r2_key, processing_status, size_bytes
|
|
||||||
FROM memories
|
|
||||||
WHERE id = ${id} AND family_id = ${familyId}
|
|
||||||
LIMIT 1
|
|
||||||
`;
|
|
||||||
if (!rows[0]) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
if (!rows[0]) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||||
|
|
||||||
const { r2_key: r2Key, size_bytes: declaredBytes } = rows[0];
|
// Mark as processing
|
||||||
|
|
||||||
// Fetch actual object size from R2 and reconcile against quota.
|
|
||||||
// This catches cases where the client lied about the file size.
|
|
||||||
let actualBytes: number | null = null;
|
|
||||||
try {
|
|
||||||
const client = makeR2Client();
|
|
||||||
const head = await client.send(
|
|
||||||
new HeadObjectCommand({ Bucket: process.env.R2_BUCKET_NAME!, Key: r2Key })
|
|
||||||
);
|
|
||||||
actualBytes = head.ContentLength ?? null;
|
|
||||||
} catch {
|
|
||||||
// If HeadObject fails the file didn't land — mark failed and return
|
|
||||||
await sql`UPDATE memories SET processing_status = 'failed', updated_at = now() WHERE id = ${id}`;
|
|
||||||
return NextResponse.json({ error: "File not found in storage after upload" }, { status: 422 });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reconcile actual size: updates size_bytes in DB and checks if family is over quota.
|
|
||||||
// reconcileActualSize() always writes the real byte count regardless of plan.
|
|
||||||
if (actualBytes !== null) {
|
|
||||||
const reconcile = await reconcileActualSize(familyId, id, actualBytes);
|
|
||||||
if (!reconcile.keep) {
|
|
||||||
// Actual size pushed family over quota — delete the object and fail the upload.
|
|
||||||
try {
|
|
||||||
const client = makeR2Client();
|
|
||||||
await client.send(
|
|
||||||
new DeleteObjectCommand({ Bucket: process.env.R2_BUCKET_NAME!, Key: r2Key })
|
|
||||||
);
|
|
||||||
} catch {
|
|
||||||
// Best-effort cleanup; log but don't block the error response.
|
|
||||||
console.error(`[quota] failed to delete over-quota object key=${r2Key}`);
|
|
||||||
}
|
|
||||||
await sql`UPDATE memories SET processing_status = 'failed', updated_at = now() WHERE id = ${id}`;
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: reconcile.reason, reason: "storage_quota_exceeded" },
|
|
||||||
{ status: 402 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Material size discrepancy check (client declared much less than actual).
|
|
||||||
// 20 % tolerance — flag in logs but don't block if within quota.
|
|
||||||
if (actualBytes !== null && declaredBytes !== null) {
|
|
||||||
const discrepancy = actualBytes - Number(declaredBytes);
|
|
||||||
if (discrepancy > Number(declaredBytes) * 0.2) {
|
|
||||||
console.warn(
|
|
||||||
`[quota] size discrepancy for memory ${id}: declared=${declaredBytes} actual=${actualBytes} delta=${discrepancy}`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Mark as processing and start the media pipeline
|
|
||||||
await sql`UPDATE memories SET processing_status = 'processing', updated_at = now() WHERE id = ${id}`;
|
await sql`UPDATE memories SET processing_status = 'processing', updated_at = now() WHERE id = ${id}`;
|
||||||
|
|
||||||
|
// Fire-and-forget: thumbnail then vision
|
||||||
generateThumbnail(id)
|
generateThumbnail(id)
|
||||||
.then(() => processMemoryVision(id))
|
.then(() => processMemoryVision(id))
|
||||||
.catch(e => console.error(`[memory pipeline] id=${id}`, e));
|
.catch(e => console.error(`[memory pipeline] id=${id}`, e));
|
||||||
|
|
||||||
return NextResponse.json({ success: true, message: "Processing started", actualBytes });
|
return NextResponse.json({ success: true, message: "Processing started" });
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,24 +0,0 @@
|
||||||
import { NextResponse } from "next/server";
|
|
||||||
import { requireFamily } from "@/lib/auth";
|
|
||||||
import { getStorageInfo, formatBytes } from "@/lib/quota";
|
|
||||||
|
|
||||||
// GET /api/storage-usage — returns storage stats for the UI meter.
|
|
||||||
// RLS-safe: requireFamily() scopes the query to the authenticated family.
|
|
||||||
export async function GET() {
|
|
||||||
const auth = await requireFamily();
|
|
||||||
if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });
|
|
||||||
|
|
||||||
const familyId = auth.session!.familyId!;
|
|
||||||
const info = await getStorageInfo(familyId);
|
|
||||||
|
|
||||||
return NextResponse.json({
|
|
||||||
usedBytes: info.usedBytes,
|
|
||||||
limitBytes: info.isPaid ? null : info.limitBytes,
|
|
||||||
usedFormatted: formatBytes(info.usedBytes),
|
|
||||||
limitFormatted: info.isPaid ? "Unlimited" : formatBytes(info.limitBytes),
|
|
||||||
fraction: info.isPaid ? 0 : info.fraction,
|
|
||||||
approaching: info.approaching,
|
|
||||||
exceeded: info.exceeded,
|
|
||||||
isPaid: info.isPaid,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
@ -4,7 +4,6 @@ import { NextRequest, NextResponse } from "next/server";
|
||||||
import { requireFamily, requireOwnership } from "@/lib/auth";
|
import { requireFamily, requireOwnership } from "@/lib/auth";
|
||||||
import { sql } from "@/db";
|
import { sql } from "@/db";
|
||||||
import { nanoid } from "nanoid";
|
import { nanoid } from "nanoid";
|
||||||
import { checkStorageQuota } from "@/lib/quota";
|
|
||||||
|
|
||||||
const ALLOWED_TYPES = ["image/jpeg", "image/jpg", "image/png", "image/webp", "image/heic", "image/gif"];
|
const ALLOWED_TYPES = ["image/jpeg", "image/jpg", "image/png", "image/webp", "image/heic", "image/gif"];
|
||||||
const MAX_BYTES = 20 * 1024 * 1024; // 20MB
|
const MAX_BYTES = 20 * 1024 * 1024; // 20MB
|
||||||
|
|
@ -60,24 +59,6 @@ export async function POST(req: NextRequest) {
|
||||||
return NextResponse.json({ error: "File too large (max 20MB)" }, { status: 400 });
|
return NextResponse.json({ error: "File too large (max 20MB)" }, { status: 400 });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Storage quota gate — must run before issuing the presigned URL.
|
|
||||||
// Client-declared sizeBytes is used for the pre-check; actual size is
|
|
||||||
// reconciled on confirm. Unknown size (0) still triggers a usage fetch
|
|
||||||
// so families already over quota are blocked even for zero-declared uploads.
|
|
||||||
const declaredBytes = sizeBytes ?? 0;
|
|
||||||
const quotaCheck = await checkStorageQuota(familyId, declaredBytes);
|
|
||||||
if (!quotaCheck.allowed) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{
|
|
||||||
error: quotaCheck.message,
|
|
||||||
reason: quotaCheck.reason,
|
|
||||||
usedBytes: quotaCheck.usedBytes,
|
|
||||||
limitBytes: quotaCheck.limitBytes,
|
|
||||||
},
|
|
||||||
{ status: 402 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (childId) {
|
if (childId) {
|
||||||
const ownership = await requireOwnership(childId, "children", "Child");
|
const ownership = await requireOwnership(childId, "children", "Child");
|
||||||
if (!ownership.success) {
|
if (!ownership.success) {
|
||||||
|
|
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 2.2 KiB |
|
|
@ -1,10 +1,9 @@
|
||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState, useEffect, use } from "react";
|
import { useState, useEffect } from "react";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
|
|
||||||
export default function InvitePage({ params }: { params: Promise<{ token: string }> }) {
|
export default function InvitePage({ params }: { params: { token: string } }) {
|
||||||
const { token } = use(params);
|
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
|
|
@ -19,7 +18,7 @@ export default function InvitePage({ params }: { params: Promise<{ token: string
|
||||||
const res = await fetch("/api/invites/accept", {
|
const res = await fetch("/api/invites/accept", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ token, userId }),
|
body: JSON.stringify({ token: params.token, userId }),
|
||||||
});
|
});
|
||||||
|
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
|
|
@ -37,7 +36,7 @@ export default function InvitePage({ params }: { params: Promise<{ token: string
|
||||||
}
|
}
|
||||||
|
|
||||||
checkInvite();
|
checkInvite();
|
||||||
}, [token, router]);
|
}, [params.token, router]);
|
||||||
|
|
||||||
if (loading) {
|
if (loading) {
|
||||||
return (
|
return (
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
import type { Metadata, Viewport } from "next";
|
import type { Metadata } from "next";
|
||||||
import { Geist, Geist_Mono, Caveat } from "next/font/google";
|
import { Geist, Geist_Mono, Caveat } from "next/font/google";
|
||||||
import "./globals.css";
|
import "./globals.css";
|
||||||
|
|
||||||
|
|
@ -18,21 +18,13 @@ const caveat = Caveat({
|
||||||
});
|
});
|
||||||
|
|
||||||
export const metadata: Metadata = {
|
export const metadata: Metadata = {
|
||||||
title: "Tia — Baby Tracker",
|
title: "Tia - Baby Tracking",
|
||||||
description: "Track feeds, sleep, milestones and memories.",
|
description: "Your baby tracking companion",
|
||||||
|
manifest: "/manifest.json",
|
||||||
icons: {
|
icons: {
|
||||||
icon: "/icon.svg",
|
icon: "/icon.svg",
|
||||||
apple: "/apple-icon.png",
|
apple: "/icon.svg",
|
||||||
},
|
},
|
||||||
appleWebApp: {
|
|
||||||
capable: true,
|
|
||||||
statusBarStyle: "default",
|
|
||||||
title: "Tia",
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
export const viewport: Viewport = {
|
|
||||||
themeColor: "#fb7185",
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function RootLayout({
|
export default function RootLayout({
|
||||||
|
|
|
||||||
|
|
@ -1,23 +0,0 @@
|
||||||
import type { MetadataRoute } from "next";
|
|
||||||
|
|
||||||
export default function manifest(): MetadataRoute.Manifest {
|
|
||||||
return {
|
|
||||||
name: "Tia — Baby Tracker",
|
|
||||||
short_name: "Tia",
|
|
||||||
description: "Track feeds, sleep, milestones and memories.",
|
|
||||||
start_url: "/?source=pwa",
|
|
||||||
display: "standalone",
|
|
||||||
background_color: "#fdf2f2",
|
|
||||||
theme_color: "#fb7185",
|
|
||||||
icons: [
|
|
||||||
{ src: "/icons/192.png", sizes: "192x192", type: "image/png" },
|
|
||||||
{ src: "/icons/512.png", sizes: "512x512", type: "image/png" },
|
|
||||||
{
|
|
||||||
src: "/icons/maskable-512.png",
|
|
||||||
sizes: "512x512",
|
|
||||||
type: "image/png",
|
|
||||||
purpose: "maskable",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
@ -1,42 +0,0 @@
|
||||||
import { defaultCache } from "@serwist/next/worker";
|
|
||||||
import type { PrecacheEntry, RuntimeCaching, SerwistGlobalConfig } from "serwist";
|
|
||||||
import { NetworkOnly, Serwist } from "serwist";
|
|
||||||
|
|
||||||
declare global {
|
|
||||||
interface WorkerGlobalScope extends SerwistGlobalConfig {
|
|
||||||
__SW_MANIFEST: (PrecacheEntry | string)[] | undefined;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
declare const self: ServiceWorkerGlobalScope;
|
|
||||||
|
|
||||||
// SECURITY: API responses carry session-protected personal/medical data.
|
|
||||||
// They must NEVER be cached. NetworkOnly = always hit the server, no cache.
|
|
||||||
// Listed first so it wins over defaultCache.
|
|
||||||
const runtimeCaching: RuntimeCaching[] = [
|
|
||||||
{
|
|
||||||
matcher: ({ sameOrigin, url }) =>
|
|
||||||
sameOrigin && url.pathname.startsWith("/api/"),
|
|
||||||
handler: new NetworkOnly(),
|
|
||||||
},
|
|
||||||
...defaultCache,
|
|
||||||
];
|
|
||||||
|
|
||||||
const serwist = new Serwist({
|
|
||||||
precacheEntries: self.__SW_MANIFEST,
|
|
||||||
precacheOptions: { cleanupOutdatedCaches: true },
|
|
||||||
skipWaiting: true,
|
|
||||||
clientsClaim: true,
|
|
||||||
navigationPreload: true,
|
|
||||||
disableDevLogs: true,
|
|
||||||
runtimeCaching,
|
|
||||||
fallbacks: {
|
|
||||||
entries: [
|
|
||||||
{
|
|
||||||
url: "/~offline",
|
|
||||||
matcher: ({ request }) => request.mode === "navigate",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
serwist.addEventListeners();
|
|
||||||
|
|
@ -1,19 +0,0 @@
|
||||||
"use client";
|
|
||||||
|
|
||||||
export default function OfflinePage() {
|
|
||||||
return (
|
|
||||||
<div className="min-h-screen flex flex-col items-center justify-center bg-gradient-to-br from-rose-50 to-amber-50 p-8 text-center">
|
|
||||||
<div className="text-6xl mb-6">🌸</div>
|
|
||||||
<h1 className="text-2xl font-bold text-rose-500 mb-3">You're offline</h1>
|
|
||||||
<p className="text-gray-600 mb-6 max-w-xs">
|
|
||||||
Reconnect to the internet to keep tracking with Tia.
|
|
||||||
</p>
|
|
||||||
<button
|
|
||||||
onClick={() => window.location.reload()}
|
|
||||||
className="px-6 py-3 bg-rose-400 text-white rounded-xl font-semibold active:opacity-80"
|
|
||||||
>
|
|
||||||
Try again
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
@ -1,115 +0,0 @@
|
||||||
"use client";
|
|
||||||
|
|
||||||
import { useEffect, useState } from "react";
|
|
||||||
|
|
||||||
// Extend the BeforeInstallPromptEvent type (not in standard lib)
|
|
||||||
interface BeforeInstallPromptEvent extends Event {
|
|
||||||
prompt(): Promise<void>;
|
|
||||||
readonly userChoice: Promise<{ outcome: "accepted" | "dismissed" }>;
|
|
||||||
}
|
|
||||||
|
|
||||||
function IOSInstallInstructions({ onDismiss }: { onDismiss: () => void }) {
|
|
||||||
return (
|
|
||||||
<div className="fixed bottom-4 left-4 right-4 z-50 bg-white border border-rose-100 rounded-2xl shadow-lg p-4">
|
|
||||||
<div className="flex justify-between items-start mb-2">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<span className="text-2xl">🌸</span>
|
|
||||||
<span className="font-semibold text-gray-900">Install Tia</span>
|
|
||||||
</div>
|
|
||||||
<button
|
|
||||||
onClick={onDismiss}
|
|
||||||
className="text-gray-400 text-xl leading-none p-1"
|
|
||||||
aria-label="Dismiss"
|
|
||||||
>
|
|
||||||
✕
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<p className="text-sm text-gray-600 mb-2">
|
|
||||||
Add Tia to your home screen for the best experience.
|
|
||||||
</p>
|
|
||||||
<div className="flex items-center gap-2 text-sm text-gray-700">
|
|
||||||
<span>Tap</span>
|
|
||||||
<span className="inline-flex items-center justify-center w-7 h-7 bg-gray-100 rounded-md text-base">⬆️</span>
|
|
||||||
<span>then</span>
|
|
||||||
<span className="font-medium">"Add to Home Screen"</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const DISMISSED_KEY = "tia_install_prompt_dismissed";
|
|
||||||
|
|
||||||
export function InstallPrompt() {
|
|
||||||
const [deferred, setDeferred] = useState<BeforeInstallPromptEvent | null>(null);
|
|
||||||
const [isIOS, setIsIOS] = useState(false);
|
|
||||||
const [dismissed, setDismissed] = useState(true); // start hidden to avoid flash
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (typeof window === "undefined") return;
|
|
||||||
|
|
||||||
const alreadyDismissed = localStorage.getItem(DISMISSED_KEY) === "1";
|
|
||||||
if (alreadyDismissed) return;
|
|
||||||
|
|
||||||
const standalone = window.matchMedia("(display-mode: standalone)").matches;
|
|
||||||
if (standalone) return; // already installed
|
|
||||||
|
|
||||||
// iOS Safari: no beforeinstallprompt, needs manual instructions
|
|
||||||
const ios = /iphone|ipad|ipod/i.test(navigator.userAgent);
|
|
||||||
const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
|
|
||||||
if (ios && isSafari) {
|
|
||||||
setIsIOS(true);
|
|
||||||
setDismissed(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Android / Chrome: capture the deferred install event
|
|
||||||
const handler = (e: Event) => {
|
|
||||||
e.preventDefault();
|
|
||||||
setDeferred(e as BeforeInstallPromptEvent);
|
|
||||||
setDismissed(false);
|
|
||||||
};
|
|
||||||
window.addEventListener("beforeinstallprompt", handler);
|
|
||||||
return () => window.removeEventListener("beforeinstallprompt", handler);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const handleDismiss = () => {
|
|
||||||
setDismissed(true);
|
|
||||||
localStorage.setItem(DISMISSED_KEY, "1");
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleInstall = async () => {
|
|
||||||
if (!deferred) return;
|
|
||||||
await deferred.prompt();
|
|
||||||
const { outcome } = await deferred.userChoice;
|
|
||||||
if (outcome === "accepted") {
|
|
||||||
setDeferred(null);
|
|
||||||
setDismissed(true);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if (dismissed) return null;
|
|
||||||
|
|
||||||
if (deferred) {
|
|
||||||
return (
|
|
||||||
<div className="fixed bottom-4 left-4 right-4 z-50 bg-white border border-rose-100 rounded-2xl shadow-lg p-4 flex items-center gap-3">
|
|
||||||
<span className="text-2xl">🌸</span>
|
|
||||||
<div className="flex-1">
|
|
||||||
<p className="font-semibold text-gray-900 text-sm">Install Tia</p>
|
|
||||||
<p className="text-xs text-gray-500">Add to home screen for quick access</p>
|
|
||||||
</div>
|
|
||||||
<button onClick={handleDismiss} className="text-gray-400 p-1 text-lg" aria-label="Dismiss">✕</button>
|
|
||||||
<button
|
|
||||||
onClick={handleInstall}
|
|
||||||
className="px-4 py-2 bg-rose-400 text-white rounded-xl text-sm font-semibold"
|
|
||||||
>
|
|
||||||
Install
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isIOS) {
|
|
||||||
return <IOSInstallInstructions onDismiss={handleDismiss} />;
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
@ -1,156 +0,0 @@
|
||||||
"use client";
|
|
||||||
|
|
||||||
import { useEffect, useState } from "react";
|
|
||||||
|
|
||||||
interface StorageInfo {
|
|
||||||
usedBytes: number;
|
|
||||||
limitBytes: number | null;
|
|
||||||
usedFormatted: string;
|
|
||||||
limitFormatted: string;
|
|
||||||
fraction: number;
|
|
||||||
approaching: boolean;
|
|
||||||
exceeded: boolean;
|
|
||||||
isPaid: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface Props {
|
|
||||||
/** If provided, used directly instead of fetching. */
|
|
||||||
info?: StorageInfo;
|
|
||||||
className?: string;
|
|
||||||
/** When true, renders nothing unless approaching or exceeded (for inline use in page headers). */
|
|
||||||
compact?: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function StorageMeter({ info: propInfo, className = "", compact = false }: Props) {
|
|
||||||
const [info, setInfo] = useState<StorageInfo | null>(propInfo ?? null);
|
|
||||||
const [loading, setLoading] = useState(!propInfo);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (propInfo) return;
|
|
||||||
fetch("/api/storage-usage")
|
|
||||||
.then(r => r.json())
|
|
||||||
.then(setInfo)
|
|
||||||
.catch(() => {})
|
|
||||||
.finally(() => setLoading(false));
|
|
||||||
}, [propInfo]);
|
|
||||||
|
|
||||||
if (loading) {
|
|
||||||
return (
|
|
||||||
<div className={`animate-pulse h-4 rounded-full bg-gray-200 dark:bg-gray-700 ${className}`} />
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!info || info.isPaid) return null;
|
|
||||||
if (compact && !info.approaching && !info.exceeded) return null;
|
|
||||||
|
|
||||||
const pct = Math.min(info.fraction * 100, 100);
|
|
||||||
const barColor = info.exceeded
|
|
||||||
? "bg-red-500"
|
|
||||||
: info.approaching
|
|
||||||
? "bg-amber-400"
|
|
||||||
: "bg-rose-400";
|
|
||||||
|
|
||||||
const textColor = info.exceeded
|
|
||||||
? "text-red-600 dark:text-red-400"
|
|
||||||
: info.approaching
|
|
||||||
? "text-amber-600 dark:text-amber-400"
|
|
||||||
: "text-gray-500 dark:text-gray-400";
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className={`space-y-1.5 ${className}`}>
|
|
||||||
{/* Label */}
|
|
||||||
<div className="flex justify-between items-center text-xs">
|
|
||||||
<span className={`font-medium ${textColor}`}>
|
|
||||||
{info.exceeded
|
|
||||||
? "Storage full"
|
|
||||||
: info.approaching
|
|
||||||
? "Storage nearly full"
|
|
||||||
: "Storage"}
|
|
||||||
</span>
|
|
||||||
<span className={textColor}>
|
|
||||||
{info.usedFormatted} / {info.limitFormatted}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Bar */}
|
|
||||||
<div className="h-1.5 rounded-full bg-gray-200 dark:bg-gray-700 overflow-hidden">
|
|
||||||
<div
|
|
||||||
className={`h-full rounded-full transition-all duration-500 ${barColor}`}
|
|
||||||
style={{ width: `${pct}%` }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Contextual message */}
|
|
||||||
{info.exceeded && (
|
|
||||||
<p className="text-xs text-red-600 dark:text-red-400">
|
|
||||||
New uploads are paused. Your existing memories are safe.{" "}
|
|
||||||
<a href="/settings#upgrade" className="underline font-medium">Upgrade</a> or delete some memories to continue.
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
{info.approaching && !info.exceeded && (
|
|
||||||
<p className="text-xs text-amber-600 dark:text-amber-400">
|
|
||||||
You've used {info.usedFormatted} of {info.limitFormatted}.
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Banner shown inline when an upload is blocked by the quota.
|
|
||||||
* Drop this next to the upload button; it only renders when blocked.
|
|
||||||
*/
|
|
||||||
export function StorageQuotaBanner({
|
|
||||||
usedBytes,
|
|
||||||
limitBytes,
|
|
||||||
usedFormatted,
|
|
||||||
limitFormatted,
|
|
||||||
}: {
|
|
||||||
usedBytes: number;
|
|
||||||
limitBytes: number;
|
|
||||||
usedFormatted: string;
|
|
||||||
limitFormatted: string;
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<div className="rounded-xl border border-red-200 bg-red-50 dark:bg-red-900/20 dark:border-red-800 p-4 space-y-1">
|
|
||||||
<p className="text-sm font-semibold text-red-700 dark:text-red-300">Storage full</p>
|
|
||||||
<p className="text-sm text-red-600 dark:text-red-400">
|
|
||||||
You've used {usedFormatted} of your {limitFormatted} free-tier storage.
|
|
||||||
Your memories are safe — new uploads are paused until you free up space or upgrade.
|
|
||||||
</p>
|
|
||||||
<a
|
|
||||||
href="/settings#upgrade"
|
|
||||||
className="inline-block mt-2 text-sm font-medium text-rose-600 dark:text-rose-400 underline"
|
|
||||||
>
|
|
||||||
Upgrade to continue uploading →
|
|
||||||
</a>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Banner for the member limit (shown when invite is blocked).
|
|
||||||
*/
|
|
||||||
export function MemberLimitBanner({
|
|
||||||
currentCount,
|
|
||||||
limit,
|
|
||||||
}: {
|
|
||||||
currentCount: number;
|
|
||||||
limit: number;
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<div className="rounded-xl border border-amber-200 bg-amber-50 dark:bg-amber-900/20 dark:border-amber-800 p-4 space-y-1">
|
|
||||||
<p className="text-sm font-semibold text-amber-700 dark:text-amber-300">Member limit reached</p>
|
|
||||||
<p className="text-sm text-amber-600 dark:text-amber-400">
|
|
||||||
Your family has {currentCount} of {limit} free-tier members. Upgrade to invite
|
|
||||||
more caregivers.
|
|
||||||
</p>
|
|
||||||
<a
|
|
||||||
href="/settings#upgrade"
|
|
||||||
className="inline-block mt-2 text-sm font-medium text-rose-600 dark:text-rose-400 underline"
|
|
||||||
>
|
|
||||||
Upgrade to add more members →
|
|
||||||
</a>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
@ -40,12 +40,8 @@ export const childStageEnum = pgEnum("child_stage", [
|
||||||
export const families = pgTable("families", {
|
export const families = pgTable("families", {
|
||||||
id: uuid("id").primaryKey().defaultRandom(),
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
name: text("name").notNull(),
|
name: text("name").notNull(),
|
||||||
// Tier / subscription — payment abstraction (migration 0005 + 0007).
|
// Tier system (legacy migration 0005_tier_system).
|
||||||
// tier: 'free' | 'pro' (or any non-'free' value = paid)
|
|
||||||
// subscriptionStatus: set by payment-provider webhook: 'active' | 'canceled' | 'past_due' | null
|
|
||||||
// All quota/member enforcement reads through isPaidFamily() in src/lib/quota.ts.
|
|
||||||
tier: varchar("tier", { length: 20 }).default("free"),
|
tier: varchar("tier", { length: 20 }).default("free"),
|
||||||
subscriptionStatus: varchar("subscription_status", { length: 20 }),
|
|
||||||
maxChildren: integer("max_children").default(1),
|
maxChildren: integer("max_children").default(1),
|
||||||
maxMembers: integer("max_members").default(2),
|
maxMembers: integer("max_members").default(2),
|
||||||
pediatricianPhone: text("pediatrician_phone"),
|
pediatricianPhone: text("pediatrician_phone"),
|
||||||
|
|
|
||||||
|
|
@ -1,7 +0,0 @@
|
||||||
/** Safe to import in client components — no server-only imports. */
|
|
||||||
export function formatBytes(bytes: number): string {
|
|
||||||
if (bytes < 1024) return `${bytes} B`;
|
|
||||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
|
||||||
if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
|
||||||
return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
|
|
||||||
}
|
|
||||||
243
src/lib/quota.ts
243
src/lib/quota.ts
|
|
@ -1,243 +0,0 @@
|
||||||
/**
|
|
||||||
* quota.ts — Storage and member-limit enforcement for Tia's free tier.
|
|
||||||
*
|
|
||||||
* Architecture:
|
|
||||||
* Pure functions (no DB I/O) → fully unit-testable without a real database.
|
|
||||||
* DB-bound functions → thin wrappers that call the pure functions
|
|
||||||
* with data fetched from Postgres.
|
|
||||||
*
|
|
||||||
* Payment abstraction:
|
|
||||||
* All enforcement reads family plan state through isPaidFamily().
|
|
||||||
* To upgrade a family, flip families.tier to any non-'free' value.
|
|
||||||
* The actual Razorpay (or other) integration only needs to call that one field.
|
|
||||||
*/
|
|
||||||
|
|
||||||
import { sql } from "@/db";
|
|
||||||
import { formatBytes } from "@/lib/format-bytes";
|
|
||||||
export { formatBytes } from "@/lib/format-bytes";
|
|
||||||
|
|
||||||
// ─── Constants ───────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export const FREE_STORAGE_LIMIT_BYTES = 1_073_741_824; // 1 GiB
|
|
||||||
export const FREE_MEMBER_LIMIT = 2;
|
|
||||||
|
|
||||||
// Storage threshold at which we show a "approaching limit" nudge (80 %).
|
|
||||||
export const STORAGE_WARN_THRESHOLD = 0.8;
|
|
||||||
|
|
||||||
// ─── Pure helpers (unit-testable, no DB) ─────────────────────────────────────
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns true if the family is on a paid plan.
|
|
||||||
* Any tier value other than 'free' (or null/undefined) is treated as paid.
|
|
||||||
* This is the single gate; swap payment providers by only touching this function.
|
|
||||||
*/
|
|
||||||
export function isPaidFamily(
|
|
||||||
tier: string | null | undefined
|
|
||||||
): boolean {
|
|
||||||
if (!tier) return false;
|
|
||||||
return tier !== "free";
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns true if adding declaredBytes would push usage over the limit.
|
|
||||||
*/
|
|
||||||
export function wouldExceedQuota(
|
|
||||||
currentUsageBytes: number,
|
|
||||||
declaredBytes: number,
|
|
||||||
limitBytes: number
|
|
||||||
): boolean {
|
|
||||||
return currentUsageBytes + declaredBytes > limitBytes;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns true if the member count is already at or over the free-tier limit.
|
|
||||||
* Paid families: always false (no enforcement).
|
|
||||||
*/
|
|
||||||
export function isAtMemberLimit(
|
|
||||||
currentCount: number,
|
|
||||||
maxMembers: number,
|
|
||||||
paid: boolean
|
|
||||||
): boolean {
|
|
||||||
if (paid) return false;
|
|
||||||
return currentCount >= maxMembers;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── Result types ─────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export type StorageQuotaResult =
|
|
||||||
| { allowed: true; usedBytes: number; limitBytes: number }
|
|
||||||
| {
|
|
||||||
allowed: false;
|
|
||||||
reason: "storage_quota_exceeded";
|
|
||||||
usedBytes: number;
|
|
||||||
limitBytes: number;
|
|
||||||
message: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type MemberLimitResult =
|
|
||||||
| { allowed: true; currentCount: number; limit: number }
|
|
||||||
| {
|
|
||||||
allowed: false;
|
|
||||||
reason: "member_limit_reached";
|
|
||||||
currentCount: number;
|
|
||||||
limit: number;
|
|
||||||
message: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export interface StorageUsageInfo {
|
|
||||||
usedBytes: number;
|
|
||||||
limitBytes: number;
|
|
||||||
/** 0–1 fraction. >1 means over quota (possible after downgrade). */
|
|
||||||
fraction: number;
|
|
||||||
approaching: boolean; // fraction >= STORAGE_WARN_THRESHOLD
|
|
||||||
exceeded: boolean; // fraction >= 1
|
|
||||||
isPaid: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── DB-bound queries ─────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Derived storage usage: SUM(size_bytes) across memories + attachments.
|
|
||||||
* Excludes memories still in 'uploading' status (file not yet in R2).
|
|
||||||
* Uses CAST to bigint to avoid integer overflow at the SQL level.
|
|
||||||
*/
|
|
||||||
export async function getFamilyStorageUsage(familyId: string): Promise<number> {
|
|
||||||
const [mRow, aRow] = await Promise.all([
|
|
||||||
sql<{ bytes: string }[]>`
|
|
||||||
SELECT COALESCE(SUM(size_bytes::bigint), 0) AS bytes
|
|
||||||
FROM memories
|
|
||||||
WHERE family_id = ${familyId}
|
|
||||||
AND processing_status != 'uploading'
|
|
||||||
AND size_bytes IS NOT NULL
|
|
||||||
`,
|
|
||||||
sql<{ bytes: string }[]>`
|
|
||||||
SELECT COALESCE(SUM(size_bytes::bigint), 0) AS bytes
|
|
||||||
FROM attachments
|
|
||||||
WHERE family_id = ${familyId}
|
|
||||||
AND size_bytes IS NOT NULL
|
|
||||||
`,
|
|
||||||
]);
|
|
||||||
return Number(mRow[0]?.bytes ?? 0) + Number(aRow[0]?.bytes ?? 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns full usage info for a family (for the storage meter UI).
|
|
||||||
*/
|
|
||||||
export async function getStorageInfo(familyId: string): Promise<StorageUsageInfo> {
|
|
||||||
const [familyRow] = await sql<{ tier: string | null }[]>`
|
|
||||||
SELECT tier FROM families WHERE id = ${familyId} LIMIT 1
|
|
||||||
`;
|
|
||||||
const paid = isPaidFamily(familyRow?.tier);
|
|
||||||
const usedBytes = await getFamilyStorageUsage(familyId);
|
|
||||||
const limitBytes = paid ? Infinity : FREE_STORAGE_LIMIT_BYTES;
|
|
||||||
const fraction = paid ? 0 : usedBytes / FREE_STORAGE_LIMIT_BYTES;
|
|
||||||
|
|
||||||
return {
|
|
||||||
usedBytes,
|
|
||||||
limitBytes,
|
|
||||||
fraction,
|
|
||||||
approaching: !paid && fraction >= STORAGE_WARN_THRESHOLD && fraction < 1,
|
|
||||||
exceeded: !paid && fraction >= 1,
|
|
||||||
isPaid: paid,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Storage quota gate — called at presigned-URL issuance.
|
|
||||||
* declaredBytes is the client-reported file size (untrusted, but used for the gate).
|
|
||||||
* On-confirm, actual size is reconciled; see reconcileActualSize().
|
|
||||||
*/
|
|
||||||
export async function checkStorageQuota(
|
|
||||||
familyId: string,
|
|
||||||
declaredBytes: number
|
|
||||||
): Promise<StorageQuotaResult> {
|
|
||||||
const [familyRow] = await sql<{ tier: string | null }[]>`
|
|
||||||
SELECT tier FROM families WHERE id = ${familyId} LIMIT 1
|
|
||||||
`;
|
|
||||||
|
|
||||||
if (isPaidFamily(familyRow?.tier)) {
|
|
||||||
const usedBytes = await getFamilyStorageUsage(familyId);
|
|
||||||
return { allowed: true, usedBytes, limitBytes: Infinity };
|
|
||||||
}
|
|
||||||
|
|
||||||
const limitBytes = FREE_STORAGE_LIMIT_BYTES;
|
|
||||||
const usedBytes = await getFamilyStorageUsage(familyId);
|
|
||||||
|
|
||||||
if (wouldExceedQuota(usedBytes, declaredBytes, limitBytes)) {
|
|
||||||
return {
|
|
||||||
allowed: false,
|
|
||||||
reason: "storage_quota_exceeded",
|
|
||||||
usedBytes,
|
|
||||||
limitBytes,
|
|
||||||
message: `Storage quota exceeded. You have used ${formatBytes(usedBytes)} of your ${formatBytes(limitBytes)} limit. Delete some memories or upgrade to continue uploading.`,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return { allowed: true, usedBytes, limitBytes };
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* After a confirmed R2 upload, checks if the actual object size would push
|
|
||||||
* the family over quota. Returns whether the upload should be kept.
|
|
||||||
*/
|
|
||||||
export async function reconcileActualSize(
|
|
||||||
familyId: string,
|
|
||||||
memoryId: string,
|
|
||||||
actualBytes: number
|
|
||||||
): Promise<{ keep: boolean; reason?: string }> {
|
|
||||||
const [familyRow] = await sql<{ tier: string | null }[]>`
|
|
||||||
SELECT tier FROM families WHERE id = ${familyId} LIMIT 1
|
|
||||||
`;
|
|
||||||
|
|
||||||
// Always update the stored size to the actual value regardless of plan
|
|
||||||
await sql`
|
|
||||||
UPDATE memories SET size_bytes = ${actualBytes} WHERE id = ${memoryId} AND family_id = ${familyId}
|
|
||||||
`;
|
|
||||||
|
|
||||||
if (isPaidFamily(familyRow?.tier)) return { keep: true };
|
|
||||||
|
|
||||||
// Re-derive usage with the updated size
|
|
||||||
const usedBytes = await getFamilyStorageUsage(familyId);
|
|
||||||
if (usedBytes > FREE_STORAGE_LIMIT_BYTES) {
|
|
||||||
return {
|
|
||||||
keep: false,
|
|
||||||
reason: `Actual file size (${formatBytes(actualBytes)}) pushed family over the ${formatBytes(FREE_STORAGE_LIMIT_BYTES)} quota.`,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return { keep: true };
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Member limit gate — called at invite creation (not acceptance).
|
|
||||||
* COUNT(family_members) is the source of truth; no separate counter.
|
|
||||||
*/
|
|
||||||
export async function checkMemberLimit(familyId: string): Promise<MemberLimitResult> {
|
|
||||||
const [row] = await sql<{ count: string; max_members: number | null; tier: string | null }[]>`
|
|
||||||
SELECT
|
|
||||||
COUNT(fm.id)::text AS count,
|
|
||||||
f.max_members,
|
|
||||||
f.tier
|
|
||||||
FROM families f
|
|
||||||
LEFT JOIN family_members fm ON fm.family_id = f.id
|
|
||||||
WHERE f.id = ${familyId}
|
|
||||||
GROUP BY f.id
|
|
||||||
`;
|
|
||||||
|
|
||||||
if (!row) return { allowed: false, reason: "member_limit_reached", currentCount: 0, limit: FREE_MEMBER_LIMIT, message: "Family not found." };
|
|
||||||
|
|
||||||
const currentCount = Number(row.count);
|
|
||||||
const limit = row.max_members ?? FREE_MEMBER_LIMIT;
|
|
||||||
|
|
||||||
if (isAtMemberLimit(currentCount, limit, isPaidFamily(row.tier))) {
|
|
||||||
return {
|
|
||||||
allowed: false,
|
|
||||||
reason: "member_limit_reached",
|
|
||||||
currentCount,
|
|
||||||
limit,
|
|
||||||
message: `Your family has reached its member limit (${currentCount}/${limit}). Upgrade to invite more caregivers.`,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return { allowed: true, currentCount, limit };
|
|
||||||
}
|
|
||||||
|
|
@ -1,18 +1,6 @@
|
||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import type { NextRequest } from "next/server";
|
import type { NextRequest } from "next/server";
|
||||||
|
|
||||||
// PWA static assets — must bypass auth entirely.
|
|
||||||
// If the SW or manifest gets a 302→login, the browser registers the login
|
|
||||||
// page as the service worker, which breaks auth for the entire PWA session.
|
|
||||||
const pwaAssets = [
|
|
||||||
"/sw.js",
|
|
||||||
"/sw.js.map",
|
|
||||||
"/manifest.webmanifest",
|
|
||||||
"/~offline",
|
|
||||||
"/icons/",
|
|
||||||
"/serwist-",
|
|
||||||
];
|
|
||||||
|
|
||||||
// Public routes that don't require authentication
|
// Public routes that don't require authentication
|
||||||
const publicRoutes = [
|
const publicRoutes = [
|
||||||
"/",
|
"/",
|
||||||
|
|
@ -45,7 +33,6 @@ const protectedApiRoutes = [
|
||||||
"/api/invites",
|
"/api/invites",
|
||||||
"/api/notifications",
|
"/api/notifications",
|
||||||
"/api/upload",
|
"/api/upload",
|
||||||
"/api/storage-usage",
|
|
||||||
"/api/chat",
|
"/api/chat",
|
||||||
"/api/history",
|
"/api/history",
|
||||||
"/api/family/members",
|
"/api/family/members",
|
||||||
|
|
@ -54,13 +41,6 @@ const protectedApiRoutes = [
|
||||||
export function middleware(request: NextRequest) {
|
export function middleware(request: NextRequest) {
|
||||||
const { pathname } = request.nextUrl;
|
const { pathname } = request.nextUrl;
|
||||||
|
|
||||||
// Always pass PWA assets through — never redirect to login
|
|
||||||
for (const asset of pwaAssets) {
|
|
||||||
if (pathname === asset || pathname.startsWith(asset)) {
|
|
||||||
return NextResponse.next();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Always allow public routes
|
// Always allow public routes
|
||||||
for (const route of publicRoutes) {
|
for (const route of publicRoutes) {
|
||||||
if (pathname === route || pathname.startsWith(route + "/")) {
|
if (pathname === route || pathname.startsWith(route + "/")) {
|
||||||
|
|
|
||||||
|
|
@ -30,5 +30,5 @@
|
||||||
".next/dev/types/**/*.ts",
|
".next/dev/types/**/*.ts",
|
||||||
"**/*.mts"
|
"**/*.mts"
|
||||||
],
|
],
|
||||||
"exclude": ["node_modules", "src/app/sw.ts"]
|
"exclude": ["node_modules"]
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,16 +0,0 @@
|
||||||
import { defineConfig } from "vitest/config";
|
|
||||||
import path from "path";
|
|
||||||
|
|
||||||
export default defineConfig({
|
|
||||||
test: {
|
|
||||||
environment: "node",
|
|
||||||
globals: true,
|
|
||||||
include: ["src/__tests__/quota.test.ts"],
|
|
||||||
exclude: ["**/node_modules/**"],
|
|
||||||
},
|
|
||||||
resolve: {
|
|
||||||
alias: {
|
|
||||||
"@": path.resolve(__dirname, "src"),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
Loading…
Add table
Reference in a new issue