Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7704924d88 | ||
|
|
7ffc2f9522 | ||
|
|
f3c6137fed |
@@ -76,6 +76,8 @@ src/
|
|||||||
|
|
||||||
**Rule for contributors (including future Codex and Claude Code sessions):** if a feature requires a change to `_core` to support a new entity type, that's a smell — extend the registry instead.
|
**Rule for contributors (including future Codex and Claude Code sessions):** if a feature requires a change to `_core` to support a new entity type, that's a smell — extend the registry instead.
|
||||||
|
|
||||||
|
**Completion rule for module additions and behavior changes:** include the authenticated v1 API and OpenAPI documentation, assistant tools backed by that API, and a complete reminder lifecycle for every user-visible due date. API, agent, and UI must call the same scoped server services; create/update must synchronize unfired reminders and delete must cancel them.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Data model (v1)
|
## Data model (v1)
|
||||||
|
|||||||
@@ -1,35 +1,5 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
## [0.6.10](https://github.com/ginnoir/famapp/compare/v0.6.9...v0.6.10) (2026-07-18)
|
|
||||||
|
|
||||||
### Features
|
|
||||||
|
|
||||||
- open notes in view mode with optional editor ([9b3bd02](https://github.com/ginnoir/famapp/commit/9b3bd02b0bafc89a514ca8fd4434f9659b9ee4c2))
|
|
||||||
|
|
||||||
## [0.6.9](https://github.com/ginnoir/famapp/compare/v0.6.8...v0.6.9) (2026-07-18)
|
|
||||||
|
|
||||||
### Bug Fixes
|
|
||||||
|
|
||||||
- build share urls from auth_url instead of localhost ([832e726](https://github.com/ginnoir/famapp/commit/832e7265c9354edf86f28f72f129ee34da8c3d04))
|
|
||||||
|
|
||||||
## [0.6.8](https://github.com/ginnoir/famapp/compare/v0.6.7...v0.6.8) (2026-07-18)
|
|
||||||
|
|
||||||
### Bug Fixes
|
|
||||||
|
|
||||||
- restore share and note scrolling on ios pwa ([969521a](https://github.com/ginnoir/famapp/commit/969521ac3f527a939988053b453881ed3560eb61))
|
|
||||||
|
|
||||||
## [0.6.7](https://github.com/ginnoir/famapp/compare/v0.6.6...v0.6.7) (2026-07-13)
|
|
||||||
|
|
||||||
### Bug Fixes
|
|
||||||
|
|
||||||
- **garden:** add ikea cabinet and acrylic case container types ([043d285](https://github.com/ginnoir/famapp/commit/043d28539ec08dd46a097970b4e876bfb1ba7aa1))
|
|
||||||
|
|
||||||
## [0.6.6](https://github.com/ginnoir/famapp/compare/v0.6.5...v0.6.6) (2026-07-13)
|
|
||||||
|
|
||||||
### Bug Fixes
|
|
||||||
|
|
||||||
- **garden:** add carnivore plant category ([b8229eb](https://github.com/ginnoir/famapp/commit/b8229eb9b5550cde98e5446615873e727ead05a8))
|
|
||||||
|
|
||||||
## [0.6.5](https://github.com/ginnoir/famapp/compare/v0.6.4...v0.6.5) (2026-07-09)
|
## [0.6.5](https://github.com/ginnoir/famapp/compare/v0.6.4...v0.6.5) (2026-07-09)
|
||||||
|
|
||||||
### Bug Fixes
|
### Bug Fixes
|
||||||
|
|||||||
@@ -77,6 +77,8 @@ src/
|
|||||||
|
|
||||||
**Rule for contributors (including future Codex and Claude Code sessions):** if a feature requires a change to `_core` to support a new entity type, that's a smell — extend the registry instead.
|
**Rule for contributors (including future Codex and Claude Code sessions):** if a feature requires a change to `_core` to support a new entity type, that's a smell — extend the registry instead.
|
||||||
|
|
||||||
|
**Completion rule for module additions and behavior changes:** include the authenticated v1 API and OpenAPI documentation, assistant tools backed by that API, and a complete reminder lifecycle for every user-visible due date. API, agent, and UI must call the same scoped server services; create/update must synchronize unfired reminders and delete must cancel them.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Data model (v1)
|
## Data model (v1)
|
||||||
|
|||||||
@@ -16,9 +16,7 @@ ENV CI=true
|
|||||||
ENV NEXT_TELEMETRY_DISABLED=1
|
ENV NEXT_TELEMETRY_DISABLED=1
|
||||||
ENV DATABASE_URL=postgres://build:build@localhost:5432/build
|
ENV DATABASE_URL=postgres://build:build@localhost:5432/build
|
||||||
ENV AUTH_SECRET=build-time-placeholder
|
ENV AUTH_SECRET=build-time-placeholder
|
||||||
# Build-only placeholder. Runtime public URL is AUTH_URL from stack.env — never prefer this.
|
|
||||||
ENV NEXT_PUBLIC_APP_URL=http://localhost:3000
|
ENV NEXT_PUBLIC_APP_URL=http://localhost:3000
|
||||||
ENV AUTH_URL=http://localhost:3000
|
|
||||||
COPY . .
|
COPY . .
|
||||||
RUN pnpm install --offline --frozen-lockfile
|
RUN pnpm install --offline --frozen-lockfile
|
||||||
RUN --mount=type=cache,id=famapp-nextjs,target=/app/.next/cache \
|
RUN --mount=type=cache,id=famapp-nextjs,target=/app/.next/cache \
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,70 @@
|
|||||||
|
-- Custom SQL migration file, put your code below! --
|
||||||
|
CREATE TABLE "pets" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"household_id" uuid NOT NULL,
|
||||||
|
"name" text NOT NULL,
|
||||||
|
"species" text NOT NULL,
|
||||||
|
"breed" text,
|
||||||
|
"birth_date" date,
|
||||||
|
"notes" text,
|
||||||
|
"primary_image_url" text,
|
||||||
|
"images" jsonb DEFAULT '[]'::jsonb NOT NULL,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
CONSTRAINT "pets_household_id_households_id_fk" FOREIGN KEY ("household_id") REFERENCES "public"."households"("id") ON DELETE cascade ON UPDATE no action
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "pet_appointments" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"pet_id" uuid NOT NULL,
|
||||||
|
"household_id" uuid NOT NULL,
|
||||||
|
"title" text NOT NULL,
|
||||||
|
"appointment_at" timestamp with time zone NOT NULL,
|
||||||
|
"clinic" text,
|
||||||
|
"notes" text,
|
||||||
|
"calendar_event_id" uuid,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
CONSTRAINT "pet_appointments_pet_id_pets_id_fk" FOREIGN KEY ("pet_id") REFERENCES "public"."pets"("id") ON DELETE cascade ON UPDATE no action,
|
||||||
|
CONSTRAINT "pet_appointments_household_id_households_id_fk" FOREIGN KEY ("household_id") REFERENCES "public"."households"("id") ON DELETE cascade ON UPDATE no action
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "pet_vaccinations" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"pet_id" uuid NOT NULL,
|
||||||
|
"household_id" uuid NOT NULL,
|
||||||
|
"name" text NOT NULL,
|
||||||
|
"administered_on" date NOT NULL,
|
||||||
|
"due_on" date,
|
||||||
|
"provider" text,
|
||||||
|
"notes" text,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
CONSTRAINT "pet_vaccinations_pet_id_pets_id_fk" FOREIGN KEY ("pet_id") REFERENCES "public"."pets"("id") ON DELETE cascade ON UPDATE no action,
|
||||||
|
CONSTRAINT "pet_vaccinations_household_id_households_id_fk" FOREIGN KEY ("household_id") REFERENCES "public"."households"("id") ON DELETE cascade ON UPDATE no action
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "pet_prescriptions" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"pet_id" uuid NOT NULL,
|
||||||
|
"household_id" uuid NOT NULL,
|
||||||
|
"medication" text NOT NULL,
|
||||||
|
"dosage" text NOT NULL,
|
||||||
|
"instructions" text,
|
||||||
|
"prescribed_on" date,
|
||||||
|
"expires_on" date,
|
||||||
|
"refills_remaining" integer,
|
||||||
|
"active" boolean DEFAULT true NOT NULL,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
CONSTRAINT "pet_prescriptions_pet_id_pets_id_fk" FOREIGN KEY ("pet_id") REFERENCES "public"."pets"("id") ON DELETE cascade ON UPDATE no action,
|
||||||
|
CONSTRAINT "pet_prescriptions_household_id_households_id_fk" FOREIGN KEY ("household_id") REFERENCES "public"."households"("id") ON DELETE cascade ON UPDATE no action
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE INDEX "pets_household_idx" ON "pets" USING btree ("household_id");
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE INDEX "pet_appointments_pet_at_idx" ON "pet_appointments" USING btree ("pet_id", "appointment_at");
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE INDEX "pet_vaccinations_pet_due_idx" ON "pet_vaccinations" USING btree ("pet_id", "due_on");
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE INDEX "pet_prescriptions_pet_active_idx" ON "pet_prescriptions" USING btree ("pet_id", "active");
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -190,6 +190,13 @@
|
|||||||
"when": 1783561000000,
|
"when": 1783561000000,
|
||||||
"tag": "0026_assistant_model_route",
|
"tag": "0026_assistant_model_route",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 27,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1783648174004,
|
||||||
|
"tag": "0027_pets_module",
|
||||||
|
"breakpoints": true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "famapp",
|
"name": "famapp",
|
||||||
"version": "0.6.10",
|
"version": "0.6.5",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"packageManager": "pnpm@10.33.3",
|
"packageManager": "pnpm@10.33.3",
|
||||||
|
|||||||
+2
-13
@@ -725,19 +725,9 @@
|
|||||||
|
|
||||||
.scroll-area {
|
.scroll-area {
|
||||||
flex: 1;
|
flex: 1;
|
||||||
overflow-x: hidden;
|
overflow: auto;
|
||||||
overflow-y: auto;
|
|
||||||
padding: 20px 24px 60px;
|
padding: 20px 24px 60px;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Bare routes (/s/*, /login, signed-out) — same scrollport as .scroll-area
|
|
||||||
without app chrome padding. Needed because html/body are overflow:hidden. */
|
|
||||||
.bare-scroll {
|
|
||||||
height: 100%;
|
|
||||||
height: 100dvh;
|
|
||||||
overflow-x: hidden;
|
|
||||||
overflow-y: auto;
|
|
||||||
}
|
|
||||||
:where(html[data-nav="bottom"]) .scroll-area,
|
:where(html[data-nav="bottom"]) .scroll-area,
|
||||||
:where(html[data-nav="fab"]) .scroll-area {
|
:where(html[data-nav="fab"]) .scroll-area {
|
||||||
padding: 12px 14px 74px;
|
padding: 12px 14px 74px;
|
||||||
@@ -1627,8 +1617,7 @@ select {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Momentum scrolling + prevent page bounce fighting in-app scroll */
|
/* Momentum scrolling + prevent page bounce fighting in-app scroll */
|
||||||
.scroll-area,
|
.scroll-area {
|
||||||
.bare-scroll {
|
|
||||||
-webkit-overflow-scrolling: touch;
|
-webkit-overflow-scrolling: touch;
|
||||||
overscroll-behavior-y: contain;
|
overscroll-behavior-y: contain;
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-14
@@ -1,5 +1,4 @@
|
|||||||
import type { Metadata, Viewport } from "next";
|
import type { Metadata, Viewport } from "next";
|
||||||
import { headers } from "next/headers";
|
|
||||||
import "./globals.css";
|
import "./globals.css";
|
||||||
import { Inter, Source_Serif_4, Newsreader, Fraunces, JetBrains_Mono } from "next/font/google";
|
import { Inter, Source_Serif_4, Newsreader, Fraunces, JetBrains_Mono } from "next/font/google";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
@@ -72,13 +71,9 @@ export const metadata: Metadata = {
|
|||||||
|
|
||||||
// Pre-paint: read user's theme prefs from localStorage and apply data-* + .dark.
|
// Pre-paint: read user's theme prefs from localStorage and apply data-* + .dark.
|
||||||
// Falls back to clay/serif-sans/regular/sidebar/system if nothing is stored.
|
// Falls back to clay/serif-sans/regular/sidebar/system if nothing is stored.
|
||||||
// Public share pages always use ink so guests get a neutral, consistent look.
|
|
||||||
const prePaintScript = `(function(){
|
const prePaintScript = `(function(){
|
||||||
try {
|
try {
|
||||||
var isShare = location.pathname.indexOf('/s/') === 0;
|
var palette = localStorage.getItem('themePalette') || localStorage.getItem('theme') || 'clay';
|
||||||
var palette = isShare
|
|
||||||
? 'ink'
|
|
||||||
: (localStorage.getItem('themePalette') || localStorage.getItem('theme') || 'clay');
|
|
||||||
var mode = localStorage.getItem('themeMode') || 'system';
|
var mode = localStorage.getItem('themeMode') || 'system';
|
||||||
var fontPair = localStorage.getItem('themeFontPair') || 'serif-sans';
|
var fontPair = localStorage.getItem('themeFontPair') || 'serif-sans';
|
||||||
var density = localStorage.getItem('themeDensity') || 'regular';
|
var density = localStorage.getItem('themeDensity') || 'regular';
|
||||||
@@ -111,10 +106,6 @@ export default async function RootLayout({ children }: { children: React.ReactNo
|
|||||||
let assistantName = DEFAULT_ASSISTANT_NAME;
|
let assistantName = DEFAULT_ASSISTANT_NAME;
|
||||||
let assistantModel: string | null = null;
|
let assistantModel: string | null = null;
|
||||||
|
|
||||||
const headersList = await headers();
|
|
||||||
const pathname = headersList.get("x-pathname") ?? "";
|
|
||||||
const isSharePage = pathname === "/s" || pathname.startsWith("/s/");
|
|
||||||
|
|
||||||
const session = await auth();
|
const session = await auth();
|
||||||
if (session?.user?.id) {
|
if (session?.user?.id) {
|
||||||
signedIn = true;
|
signedIn = true;
|
||||||
@@ -155,10 +146,6 @@ export default async function RootLayout({ children }: { children: React.ReactNo
|
|||||||
.orderBy(asc(dashboards.position), asc(dashboards.createdAt));
|
.orderBy(asc(dashboards.position), asc(dashboards.createdAt));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isSharePage) {
|
|
||||||
palette = "ink";
|
|
||||||
}
|
|
||||||
|
|
||||||
// Server-side initial dark guess: only for `dark` mode (system mode is corrected
|
// Server-side initial dark guess: only for `dark` mode (system mode is corrected
|
||||||
// before paint by the inline script). Avoids a flash on signed-in users.
|
// before paint by the inline script). Avoids a flash on signed-in users.
|
||||||
const isDark = mode === "dark";
|
const isDark = mode === "dark";
|
||||||
|
|||||||
@@ -24,8 +24,7 @@ export async function AppShell({ signedIn, navStyle, children }: Props) {
|
|||||||
|
|
||||||
if (bare || !signedIn) {
|
if (bare || !signedIn) {
|
||||||
// No shell — share viewer and signed-out pages render bare.
|
// No shell — share viewer and signed-out pages render bare.
|
||||||
// html/body are overflow:hidden for the app grid; bare pages need their own scroller.
|
return <>{children}</>;
|
||||||
return <div className="bare-scroll">{children}</div>;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const useTopVariant = navStyle === "top-nav";
|
const useTopVariant = navStyle === "top-nav";
|
||||||
|
|||||||
@@ -64,9 +64,6 @@
|
|||||||
margin: 0.8em 0;
|
margin: 0.8em 0;
|
||||||
max-width: 100%;
|
max-width: 100%;
|
||||||
overflow-x: auto;
|
overflow-x: auto;
|
||||||
overflow-y: hidden;
|
|
||||||
-webkit-overflow-scrolling: touch;
|
|
||||||
overscroll-behavior-x: contain;
|
|
||||||
padding: 0.75rem 0.9rem;
|
padding: 0.75rem 0.9rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -94,12 +91,7 @@
|
|||||||
display: block;
|
display: block;
|
||||||
margin: 0.8em 0;
|
margin: 0.8em 0;
|
||||||
max-width: 100%;
|
max-width: 100%;
|
||||||
/* overflow-x alone computes overflow-y to auto, which traps vertical
|
|
||||||
touch scrolling on iOS when a wide table fills the viewport. */
|
|
||||||
overflow-x: auto;
|
overflow-x: auto;
|
||||||
overflow-y: hidden;
|
|
||||||
-webkit-overflow-scrolling: touch;
|
|
||||||
overscroll-behavior-x: contain;
|
|
||||||
width: max-content;
|
width: max-content;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +0,0 @@
|
|||||||
/** Public origin for absolute links. AUTH_URL wins — Docker build sets NEXT_PUBLIC to localhost. */
|
|
||||||
export function getAppPublicUrl(): string {
|
|
||||||
const raw =
|
|
||||||
process.env.AUTH_URL?.trim() ||
|
|
||||||
process.env.NEXT_PUBLIC_APP_URL?.trim() ||
|
|
||||||
"http://localhost:3000";
|
|
||||||
return raw.replace(/\/$/, "");
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
export function resolveHouseholdTimezone(): string {
|
||||||
|
return process.env.HOUSEHOLD_TIMEZONE?.trim() || process.env.TZ?.trim() || "America/Chicago";
|
||||||
|
}
|
||||||
|
|
||||||
|
function part(parts: Intl.DateTimeFormatPart[], type: Intl.DateTimeFormatPartTypes): number {
|
||||||
|
const value = parts.find((item) => item.type === type)?.value;
|
||||||
|
if (!value) throw new Error(`Missing ${type} timezone part`);
|
||||||
|
return Number(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function householdDateAt(
|
||||||
|
isoDate: string,
|
||||||
|
hour: number,
|
||||||
|
timeZone = resolveHouseholdTimezone(),
|
||||||
|
): Date {
|
||||||
|
const [year, month, day] = isoDate.split("-").map(Number);
|
||||||
|
if (!year || !month || !day || hour < 0 || hour > 23) throw new Error("Invalid household date");
|
||||||
|
|
||||||
|
const candidate = Date.UTC(year, month - 1, day, hour);
|
||||||
|
const parts = new Intl.DateTimeFormat("en-US", {
|
||||||
|
timeZone,
|
||||||
|
year: "numeric",
|
||||||
|
month: "2-digit",
|
||||||
|
day: "2-digit",
|
||||||
|
hour: "2-digit",
|
||||||
|
minute: "2-digit",
|
||||||
|
second: "2-digit",
|
||||||
|
hourCycle: "h23",
|
||||||
|
}).formatToParts(new Date(candidate));
|
||||||
|
const formattedAsUtc = Date.UTC(
|
||||||
|
part(parts, "year"),
|
||||||
|
part(parts, "month") - 1,
|
||||||
|
part(parts, "day"),
|
||||||
|
part(parts, "hour"),
|
||||||
|
part(parts, "minute"),
|
||||||
|
part(parts, "second"),
|
||||||
|
);
|
||||||
|
return new Date(candidate - (formattedAsUtc - candidate));
|
||||||
|
}
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
import { createHash, randomBytes } from "crypto";
|
import { createHash, randomBytes } from "crypto";
|
||||||
import { and, eq, isNull } from "drizzle-orm";
|
import { and, eq, isNull } from "drizzle-orm";
|
||||||
import type { ApiAuthContext } from "@/lib/api-auth";
|
import type { ApiAuthContext } from "@/lib/api-auth";
|
||||||
import { getAppPublicUrl } from "@/lib/app-url";
|
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { getEntityType, getRegistry } from "./registry";
|
import { getEntityType, getRegistry } from "./registry";
|
||||||
import { shareLinks } from "./schema";
|
import { shareLinks } from "./schema";
|
||||||
@@ -28,7 +27,9 @@ function hashToken(raw: string): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function buildUrl(token: string): string {
|
function buildUrl(token: string): string {
|
||||||
return `${getAppPublicUrl()}/s/${token}`;
|
const base =
|
||||||
|
process.env["NEXT_PUBLIC_APP_URL"] ?? process.env["AUTH_URL"] ?? "http://localhost:3000";
|
||||||
|
return `${base}/s/${token}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function listShareableEntityTypes() {
|
export function listShareableEntityTypes() {
|
||||||
|
|||||||
@@ -2,7 +2,6 @@
|
|||||||
|
|
||||||
import { createHash, randomBytes } from "crypto";
|
import { createHash, randomBytes } from "crypto";
|
||||||
import { and, eq, isNull } from "drizzle-orm";
|
import { and, eq, isNull } from "drizzle-orm";
|
||||||
import { getAppPublicUrl } from "@/lib/app-url";
|
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { getCurrentSession } from "@/lib/session";
|
import { getCurrentSession } from "@/lib/session";
|
||||||
import { getEntityType } from "./registry";
|
import { getEntityType } from "./registry";
|
||||||
@@ -22,7 +21,9 @@ function hashToken(raw: string): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function buildUrl(token: string): string {
|
function buildUrl(token: string): string {
|
||||||
return `${getAppPublicUrl()}/s/${token}`;
|
const base =
|
||||||
|
process.env["NEXT_PUBLIC_APP_URL"] ?? process.env["AUTH_URL"] ?? "http://localhost:3000";
|
||||||
|
return `${base}/s/${token}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function createShareLink(
|
export async function createShareLink(
|
||||||
|
|||||||
@@ -10,8 +10,6 @@ const CONTAINER_TYPES = [
|
|||||||
{ value: "raised-bed", label: "Raised bed" },
|
{ value: "raised-bed", label: "Raised bed" },
|
||||||
{ value: "window-box", label: "Window box" },
|
{ value: "window-box", label: "Window box" },
|
||||||
{ value: "single-pot", label: "Single pot" },
|
{ value: "single-pot", label: "Single pot" },
|
||||||
{ value: "ikea-cabinet", label: "Ikea Cabinet" },
|
|
||||||
{ value: "acrylic-case", label: "Acrylic Case" },
|
|
||||||
{ value: "outdoor", label: "Outdoor" },
|
{ value: "outdoor", label: "Outdoor" },
|
||||||
{ value: "other", label: "Other" },
|
{ value: "other", label: "Other" },
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ const CATEGORIES = [
|
|||||||
{ value: "flower", label: "Flower" },
|
{ value: "flower", label: "Flower" },
|
||||||
{ value: "succulent", label: "Succulent" },
|
{ value: "succulent", label: "Succulent" },
|
||||||
{ value: "cactus", label: "Cactus" },
|
{ value: "cactus", label: "Cactus" },
|
||||||
{ value: "carnivore", label: "Carnivore" },
|
|
||||||
{ value: "tropical", label: "Tropical" },
|
{ value: "tropical", label: "Tropical" },
|
||||||
{ value: "tree", label: "Tree" },
|
{ value: "tree", label: "Tree" },
|
||||||
{ value: "shrub", label: "Shrub" },
|
{ value: "shrub", label: "Shrub" },
|
||||||
|
|||||||
@@ -2,9 +2,10 @@
|
|||||||
|
|
||||||
import dynamic from "next/dynamic";
|
import dynamic from "next/dynamic";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { Bell, Pencil, Pin, PinOff, Save, Trash2, X } from "lucide-react";
|
import { Pin, PinOff, Save, Trash2 } from "lucide-react";
|
||||||
import { useState, useTransition } from "react";
|
import { useState, useTransition } from "react";
|
||||||
import { EntityComments } from "@/components/comments/entity-comments";
|
import { EntityComments } from "@/components/comments/entity-comments";
|
||||||
|
import { RichTextContent } from "@/components/rich-text";
|
||||||
import { DetailBackLink } from "@/components/detail-back-link";
|
import { DetailBackLink } from "@/components/detail-back-link";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
@@ -12,7 +13,6 @@ import { Label } from "@/components/ui/label";
|
|||||||
import { ShareButton } from "@/components/share-button";
|
import { ShareButton } from "@/components/share-button";
|
||||||
import type { NoteDto } from "../server/queries";
|
import type { NoteDto } from "../server/queries";
|
||||||
import { createNote, deleteNote, setNotePinned, updateNote } from "../server/actions";
|
import { createNote, deleteNote, setNotePinned, updateNote } from "../server/actions";
|
||||||
import { NoteRichTextBody } from "./note-rich-text-body";
|
|
||||||
|
|
||||||
const RichTextEditor = dynamic(
|
const RichTextEditor = dynamic(
|
||||||
() => import("@/components/rich-text/rich-text-editor").then((mod) => mod.RichTextEditor),
|
() => import("@/components/rich-text/rich-text-editor").then((mod) => mod.RichTextEditor),
|
||||||
@@ -29,7 +29,6 @@ const RichTextEditor = dynamic(
|
|||||||
export function NoteEditor({ note, currentUserId }: { note?: NoteDto; currentUserId?: string }) {
|
export function NoteEditor({ note, currentUserId }: { note?: NoteDto; currentUserId?: string }) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [currentNote, setCurrentNote] = useState(note);
|
const [currentNote, setCurrentNote] = useState(note);
|
||||||
const [editing, setEditing] = useState(!note);
|
|
||||||
const [title, setTitle] = useState(note?.title ?? "");
|
const [title, setTitle] = useState(note?.title ?? "");
|
||||||
const [body, setBody] = useState(note?.body ?? "");
|
const [body, setBody] = useState(note?.body ?? "");
|
||||||
const [remindAt, setRemindAt] = useState(toLocalDateTimeValue(note?.remindAt ?? null));
|
const [remindAt, setRemindAt] = useState(toLocalDateTimeValue(note?.remindAt ?? null));
|
||||||
@@ -37,25 +36,6 @@ export function NoteEditor({ note, currentUserId }: { note?: NoteDto; currentUse
|
|||||||
|
|
||||||
const pinned = currentNote?.pinned ?? false;
|
const pinned = currentNote?.pinned ?? false;
|
||||||
|
|
||||||
function beginEdit() {
|
|
||||||
if (!currentNote) return;
|
|
||||||
setTitle(currentNote.title);
|
|
||||||
setBody(currentNote.body);
|
|
||||||
setRemindAt(toLocalDateTimeValue(currentNote.remindAt));
|
|
||||||
setEditing(true);
|
|
||||||
}
|
|
||||||
|
|
||||||
function cancelEdit() {
|
|
||||||
if (!currentNote) {
|
|
||||||
router.push("/notes");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
setTitle(currentNote.title);
|
|
||||||
setBody(currentNote.body);
|
|
||||||
setRemindAt(toLocalDateTimeValue(currentNote.remindAt));
|
|
||||||
setEditing(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
function saveNote() {
|
function saveNote() {
|
||||||
startTransition(async () => {
|
startTransition(async () => {
|
||||||
if (currentNote) {
|
if (currentNote) {
|
||||||
@@ -66,7 +46,6 @@ export function NoteEditor({ note, currentUserId }: { note?: NoteDto; currentUse
|
|||||||
remindAt: remindAt ? new Date(remindAt) : null,
|
remindAt: remindAt ? new Date(remindAt) : null,
|
||||||
});
|
});
|
||||||
setCurrentNote(updated);
|
setCurrentNote(updated);
|
||||||
setEditing(false);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -94,87 +73,38 @@ export function NoteEditor({ note, currentUserId }: { note?: NoteDto; currentUse
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const displayTitle = currentNote?.title || title || "New note";
|
|
||||||
const updatedLabel = currentNote
|
|
||||||
? new Date(currentNote.updatedAt).toLocaleDateString(undefined, {
|
|
||||||
year: "numeric",
|
|
||||||
month: "long",
|
|
||||||
day: "numeric",
|
|
||||||
})
|
|
||||||
: null;
|
|
||||||
const reminderLabel = currentNote?.remindAt
|
|
||||||
? new Date(currentNote.remindAt).toLocaleString(undefined, {
|
|
||||||
year: "numeric",
|
|
||||||
month: "short",
|
|
||||||
day: "numeric",
|
|
||||||
hour: "numeric",
|
|
||||||
minute: "2-digit",
|
|
||||||
})
|
|
||||||
: null;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="mx-auto grid w-full max-w-3xl gap-4 min-w-0">
|
<div className="mx-auto grid w-full max-w-6xl gap-4 min-w-0">
|
||||||
<DetailBackLink href="/notes" label="Notes" />
|
<DetailBackLink href="/notes" label="Notes" />
|
||||||
<header className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
|
<header className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
|
||||||
<div className="min-w-0 flex-1">
|
<div className="flex items-center gap-2 min-w-0 flex-1">
|
||||||
<div className="flex items-center gap-2 min-w-0">
|
{pinned && <Pin className="size-3.5 text-[var(--accent)]" />}
|
||||||
{pinned ? <Pin className="size-3.5 shrink-0 text-[var(--accent)]" /> : null}
|
|
||||||
<h2 className="serif text-[24px] font-medium tracking-tight truncate">
|
<h2 className="serif text-[24px] font-medium tracking-tight truncate">
|
||||||
{displayTitle}
|
{currentNote ? currentNote.title : "New note"}
|
||||||
</h2>
|
</h2>
|
||||||
</div>
|
</div>
|
||||||
{!editing && currentNote ? (
|
|
||||||
<p className="muted text-[13px] mt-1 inline-flex flex-wrap items-center gap-x-2 gap-y-1">
|
|
||||||
{pinned ? <span>Pinned</span> : null}
|
|
||||||
{pinned && updatedLabel ? <span>·</span> : null}
|
|
||||||
{updatedLabel ? <span>Updated {updatedLabel}</span> : null}
|
|
||||||
{reminderLabel ? (
|
|
||||||
<>
|
|
||||||
<span>·</span>
|
|
||||||
<span className="inline-flex items-center gap-1">
|
|
||||||
<Bell className="size-3" />
|
|
||||||
{reminderLabel}
|
|
||||||
</span>
|
|
||||||
</>
|
|
||||||
) : null}
|
|
||||||
</p>
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
<div className="flex flex-wrap gap-2">
|
<div className="flex flex-wrap gap-2">
|
||||||
{currentNote ? (
|
{currentNote ? (
|
||||||
<Button variant="outline" size="sm" onClick={togglePinned} disabled={isPending}>
|
<Button variant="outline" size="sm" onClick={togglePinned} disabled={isPending}>
|
||||||
{pinned ? <PinOff className="size-3.5" /> : <Pin className="size-3.5" />}
|
{pinned ? <PinOff className="size-3.5" /> : <Pin className="size-3.5" />}
|
||||||
{pinned ? "Unpin" : "Pin"}
|
{pinned ? "Unpin note" : "Pin note"}
|
||||||
</Button>
|
</Button>
|
||||||
) : null}
|
) : null}
|
||||||
{currentNote ? <ShareButton entityType="notes.note" entityId={currentNote.id} /> : null}
|
{currentNote ? <ShareButton entityType="notes.note" entityId={currentNote.id} /> : null}
|
||||||
{currentNote ? (
|
{currentNote ? (
|
||||||
<Button variant="destructive" size="sm" onClick={removeNote} disabled={isPending}>
|
<Button variant="destructive" size="sm" onClick={removeNote} disabled={isPending}>
|
||||||
<Trash2 className="size-3.5" />
|
<Trash2 className="size-3.5" />
|
||||||
Delete
|
Delete note
|
||||||
</Button>
|
</Button>
|
||||||
) : null}
|
) : null}
|
||||||
{editing ? (
|
|
||||||
<>
|
|
||||||
<Button variant="outline" size="sm" onClick={cancelEdit} disabled={isPending}>
|
|
||||||
<X className="size-3.5" />
|
|
||||||
Cancel
|
|
||||||
</Button>
|
|
||||||
<Button size="sm" onClick={saveNote} disabled={!title.trim() || isPending}>
|
<Button size="sm" onClick={saveNote} disabled={!title.trim() || isPending}>
|
||||||
<Save className="size-3.5" />
|
<Save className="size-3.5" />
|
||||||
Save
|
Save note
|
||||||
</Button>
|
</Button>
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<Button size="sm" onClick={beginEdit}>
|
|
||||||
<Pencil className="size-3.5" />
|
|
||||||
Edit
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
{editing ? (
|
<div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(280px,420px)] min-w-0">
|
||||||
<section
|
<section
|
||||||
className="grid gap-4 rounded-[var(--r-lg)] border-[0.5px] bg-[var(--card)] p-4 shadow-[var(--shadow-1)] min-w-0"
|
className="grid gap-4 rounded-[var(--r-lg)] border-[0.5px] bg-[var(--card)] p-4 shadow-[var(--shadow-1)] min-w-0"
|
||||||
style={{ borderColor: "var(--hair)" }}
|
style={{ borderColor: "var(--hair)" }}
|
||||||
@@ -208,18 +138,16 @@ export function NoteEditor({ note, currentUserId }: { note?: NoteDto; currentUse
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
) : currentNote ? (
|
|
||||||
<section
|
<aside
|
||||||
className="rounded-[var(--r-lg)] border-[0.5px] bg-[var(--card)] p-4 shadow-[var(--shadow-1)] min-w-0 text-[var(--ink)]"
|
className="rounded-[var(--r-lg)] border-[0.5px] bg-[var(--card)] p-4 text-[var(--ink)] shadow-[var(--shadow-1)] min-w-0"
|
||||||
style={{ borderColor: "var(--hair)" }}
|
style={{ borderColor: "var(--hair)" }}
|
||||||
|
aria-label="Preview"
|
||||||
>
|
>
|
||||||
{currentNote.body ? (
|
<div className="eyebrow mb-3">Preview</div>
|
||||||
<NoteRichTextBody noteId={currentNote.id} body={currentNote.body} />
|
<RichTextContent html={body} />
|
||||||
) : (
|
</aside>
|
||||||
<p className="text-sm muted">No body text.</p>
|
</div>
|
||||||
)}
|
|
||||||
</section>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
{currentNote && currentUserId ? (
|
{currentNote && currentUserId ? (
|
||||||
<EntityComments
|
<EntityComments
|
||||||
|
|||||||
@@ -0,0 +1,102 @@
|
|||||||
|
import {
|
||||||
|
boolean,
|
||||||
|
date,
|
||||||
|
index,
|
||||||
|
integer,
|
||||||
|
jsonb,
|
||||||
|
pgTable,
|
||||||
|
text,
|
||||||
|
timestamp,
|
||||||
|
uuid,
|
||||||
|
} from "drizzle-orm/pg-core";
|
||||||
|
import { households } from "../_core/schema";
|
||||||
|
|
||||||
|
export const pets = pgTable(
|
||||||
|
"pets",
|
||||||
|
{
|
||||||
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
householdId: uuid("household_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => households.id, { onDelete: "cascade" }),
|
||||||
|
name: text("name").notNull(),
|
||||||
|
species: text("species").notNull(),
|
||||||
|
breed: text("breed"),
|
||||||
|
birthDate: date("birth_date"),
|
||||||
|
notes: text("notes"),
|
||||||
|
primaryImageUrl: text("primary_image_url"),
|
||||||
|
images: jsonb("images").notNull().default([]).$type<string[]>(),
|
||||||
|
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
},
|
||||||
|
(table) => [index("pets_household_idx").on(table.householdId)],
|
||||||
|
);
|
||||||
|
|
||||||
|
export const petAppointments = pgTable(
|
||||||
|
"pet_appointments",
|
||||||
|
{
|
||||||
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
petId: uuid("pet_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => pets.id, { onDelete: "cascade" }),
|
||||||
|
householdId: uuid("household_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => households.id, { onDelete: "cascade" }),
|
||||||
|
title: text("title").notNull(),
|
||||||
|
appointmentAt: timestamp("appointment_at", { withTimezone: true }).notNull(),
|
||||||
|
clinic: text("clinic"),
|
||||||
|
notes: text("notes"),
|
||||||
|
calendarEventId: uuid("calendar_event_id"),
|
||||||
|
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
},
|
||||||
|
(table) => [index("pet_appointments_pet_at_idx").on(table.petId, table.appointmentAt)],
|
||||||
|
);
|
||||||
|
|
||||||
|
export const petVaccinations = pgTable(
|
||||||
|
"pet_vaccinations",
|
||||||
|
{
|
||||||
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
petId: uuid("pet_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => pets.id, { onDelete: "cascade" }),
|
||||||
|
householdId: uuid("household_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => households.id, { onDelete: "cascade" }),
|
||||||
|
name: text("name").notNull(),
|
||||||
|
administeredOn: date("administered_on").notNull(),
|
||||||
|
dueOn: date("due_on"),
|
||||||
|
provider: text("provider"),
|
||||||
|
notes: text("notes"),
|
||||||
|
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
},
|
||||||
|
(table) => [index("pet_vaccinations_pet_due_idx").on(table.petId, table.dueOn)],
|
||||||
|
);
|
||||||
|
|
||||||
|
export const petPrescriptions = pgTable(
|
||||||
|
"pet_prescriptions",
|
||||||
|
{
|
||||||
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
petId: uuid("pet_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => pets.id, { onDelete: "cascade" }),
|
||||||
|
householdId: uuid("household_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => households.id, { onDelete: "cascade" }),
|
||||||
|
medication: text("medication").notNull(),
|
||||||
|
dosage: text("dosage").notNull(),
|
||||||
|
instructions: text("instructions"),
|
||||||
|
prescribedOn: date("prescribed_on"),
|
||||||
|
expiresOn: date("expires_on"),
|
||||||
|
refillsRemaining: integer("refills_remaining"),
|
||||||
|
active: boolean("active").notNull().default(true),
|
||||||
|
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
},
|
||||||
|
(table) => [index("pet_prescriptions_pet_active_idx").on(table.petId, table.active)],
|
||||||
|
);
|
||||||
|
|
||||||
|
export type Pet = typeof pets.$inferSelect;
|
||||||
|
export type PetAppointment = typeof petAppointments.$inferSelect;
|
||||||
|
export type PetVaccination = typeof petVaccinations.$inferSelect;
|
||||||
|
export type PetPrescription = typeof petPrescriptions.$inferSelect;
|
||||||
@@ -0,0 +1,322 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import { and, eq } from "drizzle-orm";
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { z } from "zod";
|
||||||
|
import type { ApiAuthContext } from "@/lib/api-auth";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { getCurrentSession } from "@/lib/session";
|
||||||
|
import { logActivityForScope } from "@/modules/_core/activity";
|
||||||
|
import { cancelReminder, listReminderOffsets } from "@/modules/_core/reminders";
|
||||||
|
import { petAppointments, petPrescriptions, pets, petVaccinations } from "../schema";
|
||||||
|
import { syncPetAppointmentReminders, syncPetDueDateReminder } from "./reminders";
|
||||||
|
import {
|
||||||
|
appointmentInput,
|
||||||
|
appointmentUpdateInput,
|
||||||
|
petInput,
|
||||||
|
petUpdateInput,
|
||||||
|
prescriptionInput,
|
||||||
|
prescriptionUpdateInput,
|
||||||
|
vaccinationInput,
|
||||||
|
vaccinationUpdateInput,
|
||||||
|
} from "./schemas";
|
||||||
|
|
||||||
|
type Scope = Pick<ApiAuthContext, "householdId" | "userId">;
|
||||||
|
const idInput = z.object({ id: z.string().uuid() });
|
||||||
|
|
||||||
|
async function requirePet(scope: Scope, id: string) {
|
||||||
|
const [pet] = await db
|
||||||
|
.select()
|
||||||
|
.from(pets)
|
||||||
|
.where(and(eq(pets.id, id), eq(pets.householdId, scope.householdId)))
|
||||||
|
.limit(1);
|
||||||
|
if (!pet) throw new Error("Pet not found");
|
||||||
|
return pet;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function requireAppointment(scope: Scope, id: string) {
|
||||||
|
const [row] = await db
|
||||||
|
.select()
|
||||||
|
.from(petAppointments)
|
||||||
|
.where(and(eq(petAppointments.id, id), eq(petAppointments.householdId, scope.householdId)))
|
||||||
|
.limit(1);
|
||||||
|
if (!row) throw new Error("Record not found");
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
async function requireVaccination(scope: Scope, id: string) {
|
||||||
|
const [row] = await db
|
||||||
|
.select()
|
||||||
|
.from(petVaccinations)
|
||||||
|
.where(and(eq(petVaccinations.id, id), eq(petVaccinations.householdId, scope.householdId)))
|
||||||
|
.limit(1);
|
||||||
|
if (!row) throw new Error("Record not found");
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
async function requirePrescription(scope: Scope, id: string) {
|
||||||
|
const [row] = await db
|
||||||
|
.select()
|
||||||
|
.from(petPrescriptions)
|
||||||
|
.where(and(eq(petPrescriptions.id, id), eq(petPrescriptions.householdId, scope.householdId)))
|
||||||
|
.limit(1);
|
||||||
|
if (!row) throw new Error("Record not found");
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
|
||||||
|
function revalidatePet(id: string) {
|
||||||
|
revalidatePath("/pets");
|
||||||
|
revalidatePath(`/pets/${id}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createPetForScope(scope: Scope, input: z.input<typeof petInput>) {
|
||||||
|
const parsed = petInput.parse(input);
|
||||||
|
const [pet] = await db
|
||||||
|
.insert(pets)
|
||||||
|
.values({
|
||||||
|
householdId: scope.householdId,
|
||||||
|
...parsed,
|
||||||
|
breed: parsed.breed ?? null,
|
||||||
|
birthDate: parsed.birthDate ?? null,
|
||||||
|
notes: parsed.notes ?? null,
|
||||||
|
primaryImageUrl: parsed.primaryImageUrl ?? parsed.images[0] ?? null,
|
||||||
|
})
|
||||||
|
.returning();
|
||||||
|
if (!pet) throw new Error("Pet was not created");
|
||||||
|
await logActivityForScope(scope, {
|
||||||
|
entityType: "pets.pet",
|
||||||
|
entityId: pet.id,
|
||||||
|
action: "create",
|
||||||
|
payload: { name: pet.name },
|
||||||
|
});
|
||||||
|
return pet;
|
||||||
|
}
|
||||||
|
export async function createPet(input: z.input<typeof petInput>) {
|
||||||
|
const { household, user } = await getCurrentSession();
|
||||||
|
const pet = await createPetForScope({ householdId: household.id, userId: user.id }, input);
|
||||||
|
revalidatePet(pet.id);
|
||||||
|
return pet;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updatePetForScope(
|
||||||
|
scope: Scope,
|
||||||
|
input: { id: string } & z.input<typeof petUpdateInput>,
|
||||||
|
) {
|
||||||
|
const parsed = idInput.and(petUpdateInput).parse(input);
|
||||||
|
await requirePet(scope, parsed.id);
|
||||||
|
const { id, ...changes } = parsed;
|
||||||
|
await db
|
||||||
|
.update(pets)
|
||||||
|
.set({ ...changes, updatedAt: new Date() })
|
||||||
|
.where(eq(pets.id, id));
|
||||||
|
await logActivityForScope(scope, { entityType: "pets.pet", entityId: id, action: "update" });
|
||||||
|
}
|
||||||
|
export async function updatePet(input: { id: string } & z.input<typeof petUpdateInput>) {
|
||||||
|
const { household, user } = await getCurrentSession();
|
||||||
|
await updatePetForScope({ householdId: household.id, userId: user.id }, input);
|
||||||
|
revalidatePet(input.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deletePetForScope(scope: Scope, input: { id: string }) {
|
||||||
|
const { id } = idInput.parse(input);
|
||||||
|
const pet = await requirePet(scope, id);
|
||||||
|
await logActivityForScope(scope, {
|
||||||
|
entityType: "pets.pet",
|
||||||
|
entityId: id,
|
||||||
|
action: "delete",
|
||||||
|
payload: { name: pet.name },
|
||||||
|
});
|
||||||
|
await db.delete(pets).where(eq(pets.id, id));
|
||||||
|
}
|
||||||
|
export async function deletePet(input: { id: string }) {
|
||||||
|
const { household, user } = await getCurrentSession();
|
||||||
|
await deletePetForScope({ householdId: household.id, userId: user.id }, input);
|
||||||
|
revalidatePath("/pets");
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createAppointmentForScope(
|
||||||
|
scope: Scope,
|
||||||
|
input: z.input<typeof appointmentInput>,
|
||||||
|
) {
|
||||||
|
const parsed = appointmentInput.parse(input);
|
||||||
|
const pet = await requirePet(scope, parsed.petId);
|
||||||
|
const [row] = await db
|
||||||
|
.insert(petAppointments)
|
||||||
|
.values({
|
||||||
|
householdId: scope.householdId,
|
||||||
|
petId: parsed.petId,
|
||||||
|
title: parsed.title,
|
||||||
|
appointmentAt: parsed.appointmentAt,
|
||||||
|
clinic: parsed.clinic ?? null,
|
||||||
|
notes: parsed.notes ?? null,
|
||||||
|
})
|
||||||
|
.returning();
|
||||||
|
if (!row) throw new Error("Appointment was not created");
|
||||||
|
if (scope.userId)
|
||||||
|
await syncPetAppointmentReminders({
|
||||||
|
householdId: scope.householdId,
|
||||||
|
appointmentId: row.id,
|
||||||
|
appointmentAt: row.appointmentAt,
|
||||||
|
createdBy: scope.userId,
|
||||||
|
petName: pet.name,
|
||||||
|
title: row.title,
|
||||||
|
offsets: parsed.reminderOffsets,
|
||||||
|
});
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
export async function updateAppointmentForScope(
|
||||||
|
scope: Scope,
|
||||||
|
input: { id: string } & z.input<typeof appointmentUpdateInput>,
|
||||||
|
) {
|
||||||
|
const parsed = idInput.and(appointmentUpdateInput).parse(input);
|
||||||
|
const row = await requireAppointment(scope, parsed.id);
|
||||||
|
const pet = await requirePet(scope, row.petId);
|
||||||
|
const offsets = parsed.reminderOffsets ?? (await listReminderOffsets("pets.appointment", row.id));
|
||||||
|
const { id, reminderOffsets: _, ...changes } = parsed;
|
||||||
|
const [updated] = await db
|
||||||
|
.update(petAppointments)
|
||||||
|
.set({ ...changes, updatedAt: new Date() })
|
||||||
|
.where(eq(petAppointments.id, id))
|
||||||
|
.returning();
|
||||||
|
if (!updated) throw new Error("Appointment not found");
|
||||||
|
if (scope.userId)
|
||||||
|
await syncPetAppointmentReminders({
|
||||||
|
householdId: scope.householdId,
|
||||||
|
appointmentId: id,
|
||||||
|
appointmentAt: updated.appointmentAt,
|
||||||
|
createdBy: scope.userId,
|
||||||
|
petName: pet.name,
|
||||||
|
title: updated.title,
|
||||||
|
offsets,
|
||||||
|
});
|
||||||
|
return updated;
|
||||||
|
}
|
||||||
|
export async function deleteAppointmentForScope(scope: Scope, input: { id: string }) {
|
||||||
|
const { id } = idInput.parse(input);
|
||||||
|
await requireAppointment(scope, id);
|
||||||
|
await cancelReminder("pets.appointment", id);
|
||||||
|
await db.delete(petAppointments).where(eq(petAppointments.id, id));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createVaccinationForScope(
|
||||||
|
scope: Scope,
|
||||||
|
input: z.input<typeof vaccinationInput>,
|
||||||
|
) {
|
||||||
|
const parsed = vaccinationInput.parse(input);
|
||||||
|
const pet = await requirePet(scope, parsed.petId);
|
||||||
|
const [row] = await db
|
||||||
|
.insert(petVaccinations)
|
||||||
|
.values({
|
||||||
|
householdId: scope.householdId,
|
||||||
|
...parsed,
|
||||||
|
dueOn: parsed.dueOn ?? null,
|
||||||
|
provider: parsed.provider ?? null,
|
||||||
|
notes: parsed.notes ?? null,
|
||||||
|
})
|
||||||
|
.returning();
|
||||||
|
if (!row) throw new Error("Vaccination was not created");
|
||||||
|
if (scope.userId)
|
||||||
|
await syncPetDueDateReminder({
|
||||||
|
householdId: scope.householdId,
|
||||||
|
entityType: "pets.vaccination",
|
||||||
|
entityId: row.id,
|
||||||
|
dueOn: row.dueOn,
|
||||||
|
createdBy: scope.userId,
|
||||||
|
title: `Vaccination due: ${pet.name}`,
|
||||||
|
body: row.name,
|
||||||
|
});
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
export async function updateVaccinationForScope(
|
||||||
|
scope: Scope,
|
||||||
|
input: { id: string } & z.input<typeof vaccinationUpdateInput>,
|
||||||
|
) {
|
||||||
|
const parsed = idInput.and(vaccinationUpdateInput).parse(input);
|
||||||
|
const row = await requireVaccination(scope, parsed.id);
|
||||||
|
const pet = await requirePet(scope, row.petId);
|
||||||
|
const { id, ...changes } = parsed;
|
||||||
|
const [updated] = await db
|
||||||
|
.update(petVaccinations)
|
||||||
|
.set({ ...changes, updatedAt: new Date() })
|
||||||
|
.where(eq(petVaccinations.id, id))
|
||||||
|
.returning();
|
||||||
|
if (!updated) throw new Error("Vaccination not found");
|
||||||
|
if (scope.userId)
|
||||||
|
await syncPetDueDateReminder({
|
||||||
|
householdId: scope.householdId,
|
||||||
|
entityType: "pets.vaccination",
|
||||||
|
entityId: id,
|
||||||
|
dueOn: updated.dueOn,
|
||||||
|
createdBy: scope.userId,
|
||||||
|
title: `Vaccination due: ${pet.name}`,
|
||||||
|
body: updated.name,
|
||||||
|
});
|
||||||
|
return updated;
|
||||||
|
}
|
||||||
|
export async function deleteVaccinationForScope(scope: Scope, input: { id: string }) {
|
||||||
|
const { id } = idInput.parse(input);
|
||||||
|
await requireVaccination(scope, id);
|
||||||
|
await cancelReminder("pets.vaccination", id);
|
||||||
|
await db.delete(petVaccinations).where(eq(petVaccinations.id, id));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createPrescriptionForScope(
|
||||||
|
scope: Scope,
|
||||||
|
input: z.input<typeof prescriptionInput>,
|
||||||
|
) {
|
||||||
|
const parsed = prescriptionInput.parse(input);
|
||||||
|
const pet = await requirePet(scope, parsed.petId);
|
||||||
|
const [row] = await db
|
||||||
|
.insert(petPrescriptions)
|
||||||
|
.values({
|
||||||
|
householdId: scope.householdId,
|
||||||
|
...parsed,
|
||||||
|
instructions: parsed.instructions ?? null,
|
||||||
|
prescribedOn: parsed.prescribedOn ?? null,
|
||||||
|
expiresOn: parsed.expiresOn ?? null,
|
||||||
|
refillsRemaining: parsed.refillsRemaining ?? null,
|
||||||
|
})
|
||||||
|
.returning();
|
||||||
|
if (!row) throw new Error("Prescription was not created");
|
||||||
|
if (scope.userId)
|
||||||
|
await syncPetDueDateReminder({
|
||||||
|
householdId: scope.householdId,
|
||||||
|
entityType: "pets.prescription",
|
||||||
|
entityId: row.id,
|
||||||
|
dueOn: row.active ? row.expiresOn : null,
|
||||||
|
createdBy: scope.userId,
|
||||||
|
title: `Prescription due: ${pet.name}`,
|
||||||
|
body: row.medication,
|
||||||
|
});
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
export async function updatePrescriptionForScope(
|
||||||
|
scope: Scope,
|
||||||
|
input: { id: string } & z.input<typeof prescriptionUpdateInput>,
|
||||||
|
) {
|
||||||
|
const parsed = idInput.and(prescriptionUpdateInput).parse(input);
|
||||||
|
const row = await requirePrescription(scope, parsed.id);
|
||||||
|
const pet = await requirePet(scope, row.petId);
|
||||||
|
const { id, ...changes } = parsed;
|
||||||
|
const [updated] = await db
|
||||||
|
.update(petPrescriptions)
|
||||||
|
.set({ ...changes, updatedAt: new Date() })
|
||||||
|
.where(eq(petPrescriptions.id, id))
|
||||||
|
.returning();
|
||||||
|
if (!updated) throw new Error("Prescription not found");
|
||||||
|
if (scope.userId)
|
||||||
|
await syncPetDueDateReminder({
|
||||||
|
householdId: scope.householdId,
|
||||||
|
entityType: "pets.prescription",
|
||||||
|
entityId: id,
|
||||||
|
dueOn: updated.active ? updated.expiresOn : null,
|
||||||
|
createdBy: scope.userId,
|
||||||
|
title: `Prescription due: ${pet.name}`,
|
||||||
|
body: updated.medication,
|
||||||
|
});
|
||||||
|
return updated;
|
||||||
|
}
|
||||||
|
export async function deletePrescriptionForScope(scope: Scope, input: { id: string }) {
|
||||||
|
const { id } = idInput.parse(input);
|
||||||
|
await requirePrescription(scope, id);
|
||||||
|
await cancelReminder("pets.prescription", id);
|
||||||
|
await db.delete(petPrescriptions).where(eq(petPrescriptions.id, id));
|
||||||
|
}
|
||||||
@@ -0,0 +1,210 @@
|
|||||||
|
import { and, asc, desc, eq, or, sql } from "drizzle-orm";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { getCurrentSession } from "@/lib/session";
|
||||||
|
import { petAppointments, petPrescriptions, pets, petVaccinations } from "../schema";
|
||||||
|
|
||||||
|
export type PetListItemDto = {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
species: string;
|
||||||
|
breed: string | null;
|
||||||
|
primaryImageUrl: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PetAppointmentDto = {
|
||||||
|
id: string;
|
||||||
|
petId: string;
|
||||||
|
title: string;
|
||||||
|
appointmentAt: string;
|
||||||
|
clinic: string | null;
|
||||||
|
notes: string | null;
|
||||||
|
calendarEventId: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PetVaccinationDto = {
|
||||||
|
id: string;
|
||||||
|
petId: string;
|
||||||
|
name: string;
|
||||||
|
administeredOn: string;
|
||||||
|
dueOn: string | null;
|
||||||
|
provider: string | null;
|
||||||
|
notes: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PetPrescriptionDto = {
|
||||||
|
id: string;
|
||||||
|
petId: string;
|
||||||
|
medication: string;
|
||||||
|
dosage: string;
|
||||||
|
instructions: string | null;
|
||||||
|
prescribedOn: string | null;
|
||||||
|
expiresOn: string | null;
|
||||||
|
refillsRemaining: number | null;
|
||||||
|
active: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PetDetailDto = PetListItemDto & {
|
||||||
|
householdId: string;
|
||||||
|
birthDate: string | null;
|
||||||
|
notes: string | null;
|
||||||
|
images: string[];
|
||||||
|
appointments: PetAppointmentDto[];
|
||||||
|
vaccinations: PetVaccinationDto[];
|
||||||
|
prescriptions: PetPrescriptionDto[];
|
||||||
|
};
|
||||||
|
|
||||||
|
const toAppointment = (row: typeof petAppointments.$inferSelect): PetAppointmentDto => ({
|
||||||
|
id: row.id,
|
||||||
|
petId: row.petId,
|
||||||
|
title: row.title,
|
||||||
|
appointmentAt: row.appointmentAt.toISOString(),
|
||||||
|
clinic: row.clinic,
|
||||||
|
notes: row.notes,
|
||||||
|
calendarEventId: row.calendarEventId,
|
||||||
|
});
|
||||||
|
const toVaccination = (row: typeof petVaccinations.$inferSelect): PetVaccinationDto => ({
|
||||||
|
id: row.id,
|
||||||
|
petId: row.petId,
|
||||||
|
name: row.name,
|
||||||
|
administeredOn: row.administeredOn,
|
||||||
|
dueOn: row.dueOn,
|
||||||
|
provider: row.provider,
|
||||||
|
notes: row.notes,
|
||||||
|
});
|
||||||
|
const toPrescription = (row: typeof petPrescriptions.$inferSelect): PetPrescriptionDto => ({
|
||||||
|
id: row.id,
|
||||||
|
petId: row.petId,
|
||||||
|
medication: row.medication,
|
||||||
|
dosage: row.dosage,
|
||||||
|
instructions: row.instructions,
|
||||||
|
prescribedOn: row.prescribedOn,
|
||||||
|
expiresOn: row.expiresOn,
|
||||||
|
refillsRemaining: row.refillsRemaining,
|
||||||
|
active: row.active,
|
||||||
|
});
|
||||||
|
|
||||||
|
export async function listPetsForScope(householdId: string): Promise<PetListItemDto[]> {
|
||||||
|
const rows = await db
|
||||||
|
.select()
|
||||||
|
.from(pets)
|
||||||
|
.where(eq(pets.householdId, householdId))
|
||||||
|
.orderBy(asc(pets.name));
|
||||||
|
return rows.map((row) => ({
|
||||||
|
id: row.id,
|
||||||
|
name: row.name,
|
||||||
|
species: row.species,
|
||||||
|
breed: row.breed,
|
||||||
|
primaryImageUrl: row.primaryImageUrl,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listPets() {
|
||||||
|
const { household } = await getCurrentSession();
|
||||||
|
return listPetsForScope(household.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getPetForScope(
|
||||||
|
householdId: string,
|
||||||
|
id: string,
|
||||||
|
): Promise<PetDetailDto | null> {
|
||||||
|
const [pet] = await db
|
||||||
|
.select()
|
||||||
|
.from(pets)
|
||||||
|
.where(and(eq(pets.id, id), eq(pets.householdId, householdId)))
|
||||||
|
.limit(1);
|
||||||
|
if (!pet) return null;
|
||||||
|
const [appointments, vaccinations, prescriptions] = await Promise.all([
|
||||||
|
db
|
||||||
|
.select()
|
||||||
|
.from(petAppointments)
|
||||||
|
.where(and(eq(petAppointments.petId, id), eq(petAppointments.householdId, householdId)))
|
||||||
|
.orderBy(desc(petAppointments.appointmentAt)),
|
||||||
|
db
|
||||||
|
.select()
|
||||||
|
.from(petVaccinations)
|
||||||
|
.where(and(eq(petVaccinations.petId, id), eq(petVaccinations.householdId, householdId)))
|
||||||
|
.orderBy(desc(petVaccinations.administeredOn)),
|
||||||
|
db
|
||||||
|
.select()
|
||||||
|
.from(petPrescriptions)
|
||||||
|
.where(and(eq(petPrescriptions.petId, id), eq(petPrescriptions.householdId, householdId)))
|
||||||
|
.orderBy(desc(petPrescriptions.createdAt)),
|
||||||
|
]);
|
||||||
|
return {
|
||||||
|
id: pet.id,
|
||||||
|
householdId: pet.householdId,
|
||||||
|
name: pet.name,
|
||||||
|
species: pet.species,
|
||||||
|
breed: pet.breed,
|
||||||
|
birthDate: pet.birthDate,
|
||||||
|
notes: pet.notes,
|
||||||
|
primaryImageUrl: pet.primaryImageUrl,
|
||||||
|
images: pet.images,
|
||||||
|
appointments: appointments.map(toAppointment),
|
||||||
|
vaccinations: vaccinations.map(toVaccination),
|
||||||
|
prescriptions: prescriptions.map(toPrescription),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getPet(id: string) {
|
||||||
|
const { household } = await getCurrentSession();
|
||||||
|
return getPetForScope(household.id, id);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function searchPets(query: string, householdId: string) {
|
||||||
|
const term = `%${query}%`;
|
||||||
|
const rows = await db
|
||||||
|
.select({ id: pets.id, name: pets.name, species: pets.species, breed: pets.breed })
|
||||||
|
.from(pets)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(pets.householdId, householdId),
|
||||||
|
or(
|
||||||
|
sql`${pets.name} ilike ${term}`,
|
||||||
|
sql`${pets.species} ilike ${term}`,
|
||||||
|
sql`coalesce(${pets.breed}, '') ilike ${term}`,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.limit(10);
|
||||||
|
return rows.map((row) => ({
|
||||||
|
id: row.id,
|
||||||
|
title: row.name,
|
||||||
|
excerpt: [row.species, row.breed].filter(Boolean).join(" · "),
|
||||||
|
url: `/pets/${row.id}`,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getPetsOverviewStats(householdId: string) {
|
||||||
|
const [petCount] = await db
|
||||||
|
.select({ count: sql<number>`count(*)::int` })
|
||||||
|
.from(pets)
|
||||||
|
.where(eq(pets.householdId, householdId));
|
||||||
|
const [vaccinations, prescriptions] = await Promise.all([
|
||||||
|
db
|
||||||
|
.select({ count: sql<number>`count(*)::int` })
|
||||||
|
.from(petVaccinations)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(petVaccinations.householdId, householdId),
|
||||||
|
sql`${petVaccinations.dueOn} <= current_date + interval '30 days'`,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
db
|
||||||
|
.select({ count: sql<number>`count(*)::int` })
|
||||||
|
.from(petPrescriptions)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(petPrescriptions.householdId, householdId),
|
||||||
|
eq(petPrescriptions.active, true),
|
||||||
|
sql`${petPrescriptions.expiresOn} <= current_date + interval '30 days'`,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
]);
|
||||||
|
return {
|
||||||
|
petCount: Number(petCount?.count ?? 0),
|
||||||
|
dueSoonCount: Number(vaccinations[0]?.count ?? 0) + Number(prescriptions[0]?.count ?? 0),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export { toAppointment, toPrescription, toVaccination };
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import { fireAtForEventStart, normalizeReminderOffsets } from "@/lib/reminder-offsets";
|
||||||
|
import { householdDateAt } from "@/lib/household-timezone";
|
||||||
|
import {
|
||||||
|
cancelReminder,
|
||||||
|
scheduleReminder,
|
||||||
|
syncRemindersForEntity,
|
||||||
|
} from "@/modules/_core/reminders";
|
||||||
|
|
||||||
|
export async function syncPetAppointmentReminders(input: {
|
||||||
|
householdId: string;
|
||||||
|
appointmentId: string;
|
||||||
|
appointmentAt: Date;
|
||||||
|
createdBy: string;
|
||||||
|
petName: string;
|
||||||
|
title: string;
|
||||||
|
offsets: number[];
|
||||||
|
}) {
|
||||||
|
await syncRemindersForEntity({
|
||||||
|
householdId: input.householdId,
|
||||||
|
entityType: "pets.appointment",
|
||||||
|
entityId: input.appointmentId,
|
||||||
|
createdBy: input.createdBy,
|
||||||
|
reminders: normalizeReminderOffsets(input.offsets).map((offsetMinutes) => ({
|
||||||
|
fireAt: fireAtForEventStart(input.appointmentAt, offsetMinutes),
|
||||||
|
offsetMinutes,
|
||||||
|
title: `Vet visit: ${input.petName}`,
|
||||||
|
body: input.title,
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function syncPetDueDateReminder(input: {
|
||||||
|
householdId: string;
|
||||||
|
entityType: "pets.vaccination" | "pets.prescription";
|
||||||
|
entityId: string;
|
||||||
|
dueOn: string | null;
|
||||||
|
createdBy: string;
|
||||||
|
title: string;
|
||||||
|
body: string;
|
||||||
|
}) {
|
||||||
|
if (!input.dueOn) {
|
||||||
|
await cancelReminder(input.entityType, input.entityId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await scheduleReminder({
|
||||||
|
householdId: input.householdId,
|
||||||
|
entityType: input.entityType,
|
||||||
|
entityId: input.entityId,
|
||||||
|
fireAt: householdDateAt(input.dueOn, 9),
|
||||||
|
createdBy: input.createdBy,
|
||||||
|
title: input.title,
|
||||||
|
body: input.body,
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
const isoDate = z.string().regex(/^\d{4}-\d{2}-\d{2}$/);
|
||||||
|
const optionalText = (max: number) => z.string().trim().max(max).nullable().optional();
|
||||||
|
|
||||||
|
export const petInput = z.object({
|
||||||
|
name: z.string().trim().min(1).max(120),
|
||||||
|
species: z.string().trim().min(1).max(80),
|
||||||
|
breed: optionalText(120),
|
||||||
|
birthDate: isoDate.nullable().optional(),
|
||||||
|
notes: optionalText(4000),
|
||||||
|
images: z.array(z.string().min(1)).max(10).default([]),
|
||||||
|
primaryImageUrl: z.string().min(1).nullable().optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const petUpdateInput = petInput.partial();
|
||||||
|
|
||||||
|
export const appointmentInput = z.object({
|
||||||
|
petId: z.string().uuid(),
|
||||||
|
title: z.string().trim().min(1).max(160),
|
||||||
|
appointmentAt: z.coerce.date(),
|
||||||
|
clinic: optionalText(160),
|
||||||
|
notes: optionalText(4000),
|
||||||
|
reminderOffsets: z.array(z.number().int().min(0).max(43_200)).default([30]),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const appointmentUpdateInput = appointmentInput.omit({ petId: true }).partial();
|
||||||
|
|
||||||
|
export const vaccinationInput = z.object({
|
||||||
|
petId: z.string().uuid(),
|
||||||
|
name: z.string().trim().min(1).max(160),
|
||||||
|
administeredOn: isoDate,
|
||||||
|
dueOn: isoDate.nullable().optional(),
|
||||||
|
provider: optionalText(160),
|
||||||
|
notes: optionalText(4000),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const vaccinationUpdateInput = vaccinationInput.omit({ petId: true }).partial();
|
||||||
|
|
||||||
|
export const prescriptionInput = z.object({
|
||||||
|
petId: z.string().uuid(),
|
||||||
|
medication: z.string().trim().min(1).max(160),
|
||||||
|
dosage: z.string().trim().min(1).max(160),
|
||||||
|
instructions: optionalText(2000),
|
||||||
|
prescribedOn: isoDate.nullable().optional(),
|
||||||
|
expiresOn: isoDate.nullable().optional(),
|
||||||
|
refillsRemaining: z.number().int().min(0).max(99).nullable().optional(),
|
||||||
|
active: z.boolean().default(true),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const prescriptionUpdateInput = prescriptionInput.omit({ petId: true }).partial();
|
||||||
|
|
||||||
|
export const scheduleAppointmentInput = z.object({
|
||||||
|
appointmentId: z.string().uuid(),
|
||||||
|
calendarId: z.string().uuid(),
|
||||||
|
});
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import test from "node:test";
|
||||||
|
import { householdDateAt } from "../../src/lib/household-timezone";
|
||||||
|
|
||||||
|
test("householdDateAt preserves 9 AM across Chicago daylight saving time", () => {
|
||||||
|
const formatter = new Intl.DateTimeFormat("en-CA", {
|
||||||
|
timeZone: "America/Chicago",
|
||||||
|
hour: "2-digit",
|
||||||
|
minute: "2-digit",
|
||||||
|
hourCycle: "h23",
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const date of ["2026-01-15", "2026-07-15"]) {
|
||||||
|
assert.equal(formatter.format(householdDateAt(date, 9, "America/Chicago")), "09:00");
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import test from "node:test";
|
||||||
|
import {
|
||||||
|
appointmentInput,
|
||||||
|
petInput,
|
||||||
|
prescriptionInput,
|
||||||
|
scheduleAppointmentInput,
|
||||||
|
vaccinationInput,
|
||||||
|
} from "../../src/modules/pets/server/schemas";
|
||||||
|
|
||||||
|
const PET_ID = "f5a50e32-a217-4d65-ae10-98a1f441d171";
|
||||||
|
const CALENDAR_ID = "bd8e10c2-58f4-4db8-9326-0b50fdda47bb";
|
||||||
|
|
||||||
|
test("pet and medical record schemas accept bounded valid input", () => {
|
||||||
|
assert.equal(petInput.parse({ name: "Mochi", species: "cat", images: [] }).name, "Mochi");
|
||||||
|
assert.equal(
|
||||||
|
appointmentInput.parse({
|
||||||
|
petId: PET_ID,
|
||||||
|
title: "Annual exam",
|
||||||
|
appointmentAt: "2026-08-01T15:00:00.000Z",
|
||||||
|
}).title,
|
||||||
|
"Annual exam",
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
vaccinationInput.parse({ petId: PET_ID, name: "Rabies", administeredOn: "2026-07-01" }).name,
|
||||||
|
"Rabies",
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
prescriptionInput.parse({ petId: PET_ID, medication: "Apoquel", dosage: "5 mg daily" }).active,
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
assert.deepEqual(
|
||||||
|
scheduleAppointmentInput.parse({ appointmentId: PET_ID, calendarId: CALENDAR_ID }),
|
||||||
|
{
|
||||||
|
appointmentId: PET_ID,
|
||||||
|
calendarId: CALENDAR_ID,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("pet and medical record schemas reject invalid identifiers, dates, and galleries", () => {
|
||||||
|
assert.throws(() => petInput.parse({ name: "", species: "cat" }));
|
||||||
|
assert.throws(() =>
|
||||||
|
petInput.parse({
|
||||||
|
name: "Mochi",
|
||||||
|
species: "cat",
|
||||||
|
images: Array(11).fill("/api/uploads/pets/a.jpg"),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
assert.throws(() =>
|
||||||
|
appointmentInput.parse({ petId: "not-a-uuid", title: "Exam", appointmentAt: "not-a-date" }),
|
||||||
|
);
|
||||||
|
assert.throws(() =>
|
||||||
|
vaccinationInput.parse({ petId: PET_ID, name: "Rabies", administeredOn: "07/01/2026" }),
|
||||||
|
);
|
||||||
|
assert.throws(() =>
|
||||||
|
scheduleAppointmentInput.parse({ appointmentId: "bad", calendarId: "also-bad" }),
|
||||||
|
);
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user