diff --git a/.env.example b/.env.example index b28f6d5..1b383c1 100644 --- a/.env.example +++ b/.env.example @@ -8,3 +8,6 @@ LOG_LEVEL=info # Separate random secret: openssl rand -hex 32. Preserve with backups. APP_ENCRYPTION_KEY= + +# Raise the reverse proxy body limit too if increasing this value. +ATTACHMENT_MAX_BYTES=50000000 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..d72fd52 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +*.pdf binary diff --git a/README.md b/README.md index 51dab0a..8838deb 100644 --- a/README.md +++ b/README.md @@ -4,15 +4,21 @@ A self-hosted household task manager: simple daily use, powerful planning when n English/Swedish, mobile and desktop, and portable Docker deployment. Licensed under [AGPL-3.0-or-later](LICENSE). -**Development status:** Stage 3 task capture and planning foundation. This is not yet the Milestone 1 Viable -Product. Accounts, shared entities, task capture, six columns and guarded autosave are implemented; hierarchy, filters and the remaining workflows follow in the approved stages. M1 retains the complete approved -scope; automatic GPS and notifications follow in M2, and integrated cloud backup in M4. +**Development status:** Stages 1–3, 7 and 5 are implemented. Rich text, +comments/mentions, files/photos, search and live household synchronization are locally +tested. Shared filters/views and Board interactions are locally tested. +**Stage 4 (hierarchy/inheritance/dependencies) is next**, followed by **6 → 8**. This is not +yet the complete Milestone 1 Viable Product. Stages 7 and 5 are prioritized for +meaningful household use and evaluation; the full M1 scope remains unchanged. +Automatic GPS and notifications follow in M2, integrated cloud backup in M4. ## Start here - [Developer setup](docs/development.md) - [Deployment and operations](docs/operations.md) - [Approved delivery stages and acceptance mapping](docs/implementation/delivery-stages.md) +- [Stage 7 review](docs/implementation/stage-7-review.md) +- [Stage 5 review](docs/implementation/stage-5-review.md) - [Stage 3 review](docs/implementation/stage-3-review.md) - [Stage 2 review](docs/implementation/stage-2-review.md) - [Stage 1 review](docs/implementation/stage-1-review.md) diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 5236c04..1798c18 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -14,3 +14,10 @@ Runtime/development packages retain their upstream license files in dependency p Review the generated dependency inventory under docs/dependencies.json before release. The inventory records declared SPDX metadata, not a substitute for checking licenses when adding dependencies. Container base images also carry upstream notices. + +Stage 7 adds Tiptap/ProseMirror editor packages (MIT), sharp (Apache-2.0), +heic-convert/heic-decode (ISC) and libheif-js (LGPL-3.0), together with their +transitive dependencies. The unmodified libheif-js package supplies the HEIC decoder; +its upstream source and license references are retained in the distributed dependency +package. Image fixtures under tests/fixtures were generated for Tendly; they do not +contain third-party photographs. diff --git a/apps/api/drizzle/0004_eager_ulik.sql b/apps/api/drizzle/0004_eager_ulik.sql new file mode 100644 index 0000000..bd6c133 --- /dev/null +++ b/apps/api/drizzle/0004_eager_ulik.sql @@ -0,0 +1,33 @@ +CREATE TABLE "attachments" ( + "id" uuid PRIMARY KEY NOT NULL, + "household_id" uuid NOT NULL, + "task_id" uuid NOT NULL, + "name" text NOT NULL, + "mime" text NOT NULL, + "size" integer NOT NULL, + "preview" boolean DEFAULT false NOT NULL, + "version" integer DEFAULT 1 NOT NULL, + "deleted" boolean DEFAULT false NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE "task_comments" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "task_id" uuid NOT NULL, + "author_id" uuid, + "body" jsonb NOT NULL, + "version" integer DEFAULT 1 NOT NULL, + "deleted" boolean DEFAULT false NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +ALTER TABLE "tasks" ALTER COLUMN "description" DROP DEFAULT;--> statement-breakpoint +ALTER TABLE "tasks" ALTER COLUMN "description" SET DATA TYPE jsonb USING to_jsonb("description");--> statement-breakpoint +ALTER TABLE "tasks" ALTER COLUMN "description" SET DEFAULT '""'::jsonb;--> statement-breakpoint +ALTER TABLE "attachments" ADD CONSTRAINT "attachments_household_id_households_id_fk" FOREIGN KEY ("household_id") REFERENCES "public"."households"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "attachments" ADD CONSTRAINT "attachments_task_id_tasks_id_fk" FOREIGN KEY ("task_id") REFERENCES "public"."tasks"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "task_comments" ADD CONSTRAINT "task_comments_task_id_tasks_id_fk" FOREIGN KEY ("task_id") REFERENCES "public"."tasks"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "task_comments" ADD CONSTRAINT "task_comments_author_id_users_id_fk" FOREIGN KEY ("author_id") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint +CREATE INDEX "attachment_task_idx" ON "attachments" USING btree ("task_id");--> statement-breakpoint +CREATE INDEX "comment_task_idx" ON "task_comments" USING btree ("task_id","created_at"); \ No newline at end of file diff --git a/apps/api/drizzle/0005_jazzy_blue_shield.sql b/apps/api/drizzle/0005_jazzy_blue_shield.sql new file mode 100644 index 0000000..90ec3ca --- /dev/null +++ b/apps/api/drizzle/0005_jazzy_blue_shield.sql @@ -0,0 +1,77 @@ +CREATE TABLE "filter_versions" ( + "filter_id" uuid NOT NULL, + "version" integer NOT NULL, + "author_id" uuid, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "snapshot" jsonb NOT NULL, + CONSTRAINT "filter_versions_filter_id_version_pk" PRIMARY KEY("filter_id","version") +); +--> statement-breakpoint +CREATE TABLE "saved_filters" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "household_id" uuid NOT NULL, + "creator_id" uuid, + "name" text NOT NULL, + "icon" text NOT NULL, + "color" text NOT NULL, + "builtin" text, + "version" integer DEFAULT 1 NOT NULL, + "deleted" boolean DEFAULT false NOT NULL, + "expression" jsonb NOT NULL +); +--> statement-breakpoint +CREATE TABLE "task_order_versions" ( + "household_id" uuid PRIMARY KEY NOT NULL, + "version" integer DEFAULT 0 NOT NULL +); +--> statement-breakpoint +CREATE TABLE "user_view_contexts" ( + "household_id" uuid NOT NULL, + "user_id" uuid NOT NULL, + "version" integer DEFAULT 1 NOT NULL, + "current_place_id" uuid, + CONSTRAINT "user_view_contexts_household_id_user_id_pk" PRIMARY KEY("household_id","user_id") +); +--> statement-breakpoint +CREATE TABLE "user_view_states" ( + "view_id" uuid NOT NULL, + "user_id" uuid NOT NULL, + "version" integer DEFAULT 1 NOT NULL, + "favorite" boolean DEFAULT false NOT NULL, + "active_filters" jsonb DEFAULT '[]'::jsonb NOT NULL, + CONSTRAINT "user_view_states_view_id_user_id_pk" PRIMARY KEY("view_id","user_id") +); +--> statement-breakpoint +CREATE TABLE "saved_views" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "household_id" uuid NOT NULL, + "creator_id" uuid, + "name" text NOT NULL, + "icon" text NOT NULL, + "color" text NOT NULL, + "builtin" text, + "version" integer DEFAULT 1 NOT NULL, + "deleted" boolean DEFAULT false NOT NULL, + "presentation" text NOT NULL, + "expression" jsonb NOT NULL, + "quick_filters" jsonb DEFAULT '[]'::jsonb NOT NULL, + "sort" text DEFAULT 'manual' NOT NULL, + "epic_lanes" boolean DEFAULT false NOT NULL, + "show_empty_lanes" boolean DEFAULT false NOT NULL, + "card_properties" jsonb NOT NULL +); +--> statement-breakpoint +ALTER TABLE "filter_versions" ADD CONSTRAINT "filter_versions_filter_id_saved_filters_id_fk" FOREIGN KEY ("filter_id") REFERENCES "public"."saved_filters"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "filter_versions" ADD CONSTRAINT "filter_versions_author_id_users_id_fk" FOREIGN KEY ("author_id") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "saved_filters" ADD CONSTRAINT "saved_filters_household_id_households_id_fk" FOREIGN KEY ("household_id") REFERENCES "public"."households"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "saved_filters" ADD CONSTRAINT "saved_filters_creator_id_users_id_fk" FOREIGN KEY ("creator_id") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "task_order_versions" ADD CONSTRAINT "task_order_versions_household_id_households_id_fk" FOREIGN KEY ("household_id") REFERENCES "public"."households"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "user_view_contexts" ADD CONSTRAINT "user_view_contexts_household_id_households_id_fk" FOREIGN KEY ("household_id") REFERENCES "public"."households"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "user_view_contexts" ADD CONSTRAINT "user_view_contexts_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "user_view_contexts" ADD CONSTRAINT "user_view_contexts_current_place_id_planning_entities_id_fk" FOREIGN KEY ("current_place_id") REFERENCES "public"."planning_entities"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "user_view_states" ADD CONSTRAINT "user_view_states_view_id_saved_views_id_fk" FOREIGN KEY ("view_id") REFERENCES "public"."saved_views"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "user_view_states" ADD CONSTRAINT "user_view_states_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "saved_views" ADD CONSTRAINT "saved_views_household_id_households_id_fk" FOREIGN KEY ("household_id") REFERENCES "public"."households"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "saved_views" ADD CONSTRAINT "saved_views_creator_id_users_id_fk" FOREIGN KEY ("creator_id") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint +CREATE UNIQUE INDEX "filter_builtin_idx" ON "saved_filters" USING btree ("household_id","builtin");--> statement-breakpoint +CREATE UNIQUE INDEX "view_builtin_idx" ON "saved_views" USING btree ("household_id","builtin"); \ No newline at end of file diff --git a/apps/api/drizzle/meta/0004_snapshot.json b/apps/api/drizzle/meta/0004_snapshot.json new file mode 100644 index 0000000..51f4bce --- /dev/null +++ b/apps/api/drizzle/meta/0004_snapshot.json @@ -0,0 +1,1565 @@ +{ + "id": "c7873a3e-efdf-4c60-aa29-5dfb63163254", + "prevId": "149e2d32-dc44-4c97-9a08-ca17dbbc0a6c", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.installation": { + "name": "installation", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.auth_challenges": { + "name": "auth_challenges", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "challenge": { + "name": "challenge", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "binding_hash": { + "name": "binding_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "context": { + "name": "context", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.passkey_credentials": { + "name": "passkey_credentials", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "public_key": { + "name": "public_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "counter": { + "name": "counter", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "transports": { + "name": "transports", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "credential_user_idx": { + "name": "credential_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "passkey_credentials_user_id_users_id_fk": { + "name": "passkey_credentials_user_id_users_id_fk", + "tableFrom": "passkey_credentials", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.households": { + "name": "households", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.memberships": { + "name": "memberships", + "schema": "", + "columns": { + "household_id": { + "name": "household_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "household_role", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "membership_user_idx": { + "name": "membership_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "memberships_household_id_households_id_fk": { + "name": "memberships_household_id_households_id_fk", + "tableFrom": "memberships", + "tableTo": "households", + "columnsFrom": [ + "household_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "memberships_user_id_users_id_fk": { + "name": "memberships_user_id_users_id_fk", + "tableFrom": "memberships", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "memberships_household_id_user_id_pk": { + "name": "memberships_household_id_user_id_pk", + "columns": [ + "household_id", + "user_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.security_events": { + "name": "security_events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "actor_id": { + "name": "actor_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "subject_id": { + "name": "subject_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "security_events_actor_id_users_id_fk": { + "name": "security_events_actor_id_users_id_fk", + "tableFrom": "security_events", + "tableTo": "users", + "columnsFrom": [ + "actor_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "security_events_subject_id_users_id_fk": { + "name": "security_events_subject_id_users_id_fk", + "tableFrom": "security_events", + "tableTo": "users", + "columnsFrom": [ + "subject_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sessions": { + "name": "sessions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "authenticated_at": { + "name": "authenticated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "session_user_idx": { + "name": "session_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "sessions_user_id_users_id_fk": { + "name": "sessions_user_id_users_id_fk", + "tableFrom": "sessions", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.smtp_settings": { + "name": "smtp_settings", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true + }, + "encrypted": { + "name": "encrypted", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.account_tokens": { + "name": "account_tokens", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "purpose": { + "name": "purpose", + "type": "token_purpose", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "verifies_email": { + "name": "verifies_email", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "household_id": { + "name": "household_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "role": { + "name": "role", + "type": "household_role", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "used_at": { + "name": "used_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "account_tokens_user_id_users_id_fk": { + "name": "account_tokens_user_id_users_id_fk", + "tableFrom": "account_tokens", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "account_tokens_household_id_households_id_fk": { + "name": "account_tokens_household_id_households_id_fk", + "tableFrom": "account_tokens", + "tableTo": "households", + "columnsFrom": [ + "household_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.users": { + "name": "users", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email_verified_at": { + "name": "email_verified_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "deployment_admin": { + "name": "deployment_admin", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "language": { + "name": "language", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'en'" + }, + "theme": { + "name": "theme", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'system'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "users_email_unique": { + "name": "users_email_unique", + "nullsNotDistinct": false, + "columns": [ + "email" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.planning_entities": { + "name": "planning_entities", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "household_id": { + "name": "household_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "entity_kind", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "icon": { + "name": "icon", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'house'" + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'blue'" + }, + "archived": { + "name": "archived", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "latitude": { + "name": "latitude", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "longitude": { + "name": "longitude", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "radius": { + "name": "radius", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "sort_order": { + "name": "sort_order", + "type": "double precision", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "entity_household_idx": { + "name": "entity_household_idx", + "columns": [ + { + "expression": "household_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "kind", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sort_order", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "planning_entities_household_id_households_id_fk": { + "name": "planning_entities_household_id_households_id_fk", + "tableFrom": "planning_entities", + "tableTo": "households", + "columnsFrom": [ + "household_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.planning_settings": { + "name": "planning_settings", + "schema": "", + "columns": { + "household_id": { + "name": "household_id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "size_thresholds": { + "name": "size_thresholds", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[60,240,480,1440]'::jsonb" + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + } + }, + "indexes": {}, + "foreignKeys": { + "planning_settings_household_id_households_id_fk": { + "name": "planning_settings_household_id_households_id_fk", + "tableFrom": "planning_settings", + "tableTo": "households", + "columnsFrom": [ + "household_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.task_activities": { + "name": "task_activities", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "task_id": { + "name": "task_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "actor_id": { + "name": "actor_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "fields": { + "name": "fields", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "task_activities_task_id_tasks_id_fk": { + "name": "task_activities_task_id_tasks_id_fk", + "tableFrom": "task_activities", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "task_activities_actor_id_users_id_fk": { + "name": "task_activities_actor_id_users_id_fk", + "tableFrom": "task_activities", + "tableTo": "users", + "columnsFrom": [ + "actor_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.task_assignees": { + "name": "task_assignees", + "schema": "", + "columns": { + "task_id": { + "name": "task_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "task_assignees_task_id_tasks_id_fk": { + "name": "task_assignees_task_id_tasks_id_fk", + "tableFrom": "task_assignees", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "task_assignees_user_id_users_id_fk": { + "name": "task_assignees_user_id_users_id_fk", + "tableFrom": "task_assignees", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "task_assignees_task_id_user_id_pk": { + "name": "task_assignees_task_id_user_id_pk", + "columns": [ + "task_id", + "user_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.task_entities": { + "name": "task_entities", + "schema": "", + "columns": { + "task_id": { + "name": "task_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "entity_id": { + "name": "entity_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "task_entities_task_id_tasks_id_fk": { + "name": "task_entities_task_id_tasks_id_fk", + "tableFrom": "task_entities", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "task_entities_entity_id_planning_entities_id_fk": { + "name": "task_entities_entity_id_planning_entities_id_fk", + "tableFrom": "task_entities", + "tableTo": "planning_entities", + "columnsFrom": [ + "entity_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "task_entities_task_id_entity_id_pk": { + "name": "task_entities_task_id_entity_id_pk", + "columns": [ + "task_id", + "entity_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tasks": { + "name": "tasks", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "household_id": { + "name": "household_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "status": { + "name": "status", + "type": "task_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'todo'" + }, + "planning_bucket": { + "name": "planning_bucket", + "type": "planning_bucket", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'someday'" + }, + "preceding_column": { + "name": "preceding_column", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "epic_id": { + "name": "epic_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "high": { + "name": "high", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "size": { + "name": "size", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "estimate_minutes": { + "name": "estimate_minutes", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "start_date": { + "name": "start_date", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "start_time": { + "name": "start_time", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "deadline_date": { + "name": "deadline_date", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "deadline_time": { + "name": "deadline_time", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "field_versions": { + "name": "field_versions", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "sort_order": { + "name": "sort_order", + "type": "double precision", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_by": { + "name": "created_by", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "completed_by": { + "name": "completed_by", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "trashed_at": { + "name": "trashed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "task_household_order_idx": { + "name": "task_household_order_idx", + "columns": [ + { + "expression": "household_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sort_order", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "task_epic_idx": { + "name": "task_epic_idx", + "columns": [ + { + "expression": "epic_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "tasks_household_id_households_id_fk": { + "name": "tasks_household_id_households_id_fk", + "tableFrom": "tasks", + "tableTo": "households", + "columnsFrom": [ + "household_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tasks_epic_id_planning_entities_id_fk": { + "name": "tasks_epic_id_planning_entities_id_fk", + "tableFrom": "tasks", + "tableTo": "planning_entities", + "columnsFrom": [ + "epic_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "tasks_created_by_users_id_fk": { + "name": "tasks_created_by_users_id_fk", + "tableFrom": "tasks", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "tasks_completed_by_users_id_fk": { + "name": "tasks_completed_by_users_id_fk", + "tableFrom": "tasks", + "tableTo": "users", + "columnsFrom": [ + "completed_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.attachments": { + "name": "attachments", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "household_id": { + "name": "household_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "task_id": { + "name": "task_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "mime": { + "name": "mime", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "size": { + "name": "size", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "preview": { + "name": "preview", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "deleted": { + "name": "deleted", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "attachment_task_idx": { + "name": "attachment_task_idx", + "columns": [ + { + "expression": "task_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "attachments_household_id_households_id_fk": { + "name": "attachments_household_id_households_id_fk", + "tableFrom": "attachments", + "tableTo": "households", + "columnsFrom": [ + "household_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "attachments_task_id_tasks_id_fk": { + "name": "attachments_task_id_tasks_id_fk", + "tableFrom": "attachments", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.task_comments": { + "name": "task_comments", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "task_id": { + "name": "task_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "author_id": { + "name": "author_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "body": { + "name": "body", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "deleted": { + "name": "deleted", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "comment_task_idx": { + "name": "comment_task_idx", + "columns": [ + { + "expression": "task_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "task_comments_task_id_tasks_id_fk": { + "name": "task_comments_task_id_tasks_id_fk", + "tableFrom": "task_comments", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "task_comments_author_id_users_id_fk": { + "name": "task_comments_author_id_users_id_fk", + "tableFrom": "task_comments", + "tableTo": "users", + "columnsFrom": [ + "author_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": { + "public.household_role": { + "name": "household_role", + "schema": "public", + "values": [ + "admin", + "member" + ] + }, + "public.token_purpose": { + "name": "token_purpose", + "schema": "public", + "values": [ + "bootstrap", + "invite", + "recovery", + "verify_email" + ] + }, + "public.planning_bucket": { + "name": "planning_bucket", + "schema": "public", + "values": [ + "someday", + "within_year", + "within_month", + "ready" + ] + }, + "public.entity_kind": { + "name": "entity_kind", + "schema": "public", + "values": [ + "epic", + "place", + "resource", + "tag" + ] + }, + "public.task_status": { + "name": "task_status", + "schema": "public", + "values": [ + "todo", + "in_progress", + "done" + ] + } + }, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/apps/api/drizzle/meta/0005_snapshot.json b/apps/api/drizzle/meta/0005_snapshot.json new file mode 100644 index 0000000..3dab5c5 --- /dev/null +++ b/apps/api/drizzle/meta/0005_snapshot.json @@ -0,0 +1,2141 @@ +{ + "id": "0fbf5761-8ace-4331-80f3-4c26d60d2a10", + "prevId": "c7873a3e-efdf-4c60-aa29-5dfb63163254", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.installation": { + "name": "installation", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.auth_challenges": { + "name": "auth_challenges", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "challenge": { + "name": "challenge", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "binding_hash": { + "name": "binding_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "context": { + "name": "context", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.passkey_credentials": { + "name": "passkey_credentials", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "public_key": { + "name": "public_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "counter": { + "name": "counter", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "transports": { + "name": "transports", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "credential_user_idx": { + "name": "credential_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "passkey_credentials_user_id_users_id_fk": { + "name": "passkey_credentials_user_id_users_id_fk", + "tableFrom": "passkey_credentials", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.households": { + "name": "households", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.memberships": { + "name": "memberships", + "schema": "", + "columns": { + "household_id": { + "name": "household_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "household_role", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "membership_user_idx": { + "name": "membership_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "memberships_household_id_households_id_fk": { + "name": "memberships_household_id_households_id_fk", + "tableFrom": "memberships", + "tableTo": "households", + "columnsFrom": [ + "household_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "memberships_user_id_users_id_fk": { + "name": "memberships_user_id_users_id_fk", + "tableFrom": "memberships", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "memberships_household_id_user_id_pk": { + "name": "memberships_household_id_user_id_pk", + "columns": [ + "household_id", + "user_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.security_events": { + "name": "security_events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "actor_id": { + "name": "actor_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "subject_id": { + "name": "subject_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "security_events_actor_id_users_id_fk": { + "name": "security_events_actor_id_users_id_fk", + "tableFrom": "security_events", + "tableTo": "users", + "columnsFrom": [ + "actor_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "security_events_subject_id_users_id_fk": { + "name": "security_events_subject_id_users_id_fk", + "tableFrom": "security_events", + "tableTo": "users", + "columnsFrom": [ + "subject_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sessions": { + "name": "sessions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "authenticated_at": { + "name": "authenticated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "session_user_idx": { + "name": "session_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "sessions_user_id_users_id_fk": { + "name": "sessions_user_id_users_id_fk", + "tableFrom": "sessions", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.smtp_settings": { + "name": "smtp_settings", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true + }, + "encrypted": { + "name": "encrypted", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.account_tokens": { + "name": "account_tokens", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "purpose": { + "name": "purpose", + "type": "token_purpose", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "verifies_email": { + "name": "verifies_email", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "household_id": { + "name": "household_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "role": { + "name": "role", + "type": "household_role", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "used_at": { + "name": "used_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "account_tokens_user_id_users_id_fk": { + "name": "account_tokens_user_id_users_id_fk", + "tableFrom": "account_tokens", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "account_tokens_household_id_households_id_fk": { + "name": "account_tokens_household_id_households_id_fk", + "tableFrom": "account_tokens", + "tableTo": "households", + "columnsFrom": [ + "household_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.users": { + "name": "users", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email_verified_at": { + "name": "email_verified_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "deployment_admin": { + "name": "deployment_admin", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "language": { + "name": "language", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'en'" + }, + "theme": { + "name": "theme", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'system'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "users_email_unique": { + "name": "users_email_unique", + "nullsNotDistinct": false, + "columns": [ + "email" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.planning_entities": { + "name": "planning_entities", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "household_id": { + "name": "household_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "entity_kind", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "icon": { + "name": "icon", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'house'" + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'blue'" + }, + "archived": { + "name": "archived", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "latitude": { + "name": "latitude", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "longitude": { + "name": "longitude", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "radius": { + "name": "radius", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "sort_order": { + "name": "sort_order", + "type": "double precision", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "entity_household_idx": { + "name": "entity_household_idx", + "columns": [ + { + "expression": "household_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "kind", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sort_order", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "planning_entities_household_id_households_id_fk": { + "name": "planning_entities_household_id_households_id_fk", + "tableFrom": "planning_entities", + "tableTo": "households", + "columnsFrom": [ + "household_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.planning_settings": { + "name": "planning_settings", + "schema": "", + "columns": { + "household_id": { + "name": "household_id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "size_thresholds": { + "name": "size_thresholds", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[60,240,480,1440]'::jsonb" + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + } + }, + "indexes": {}, + "foreignKeys": { + "planning_settings_household_id_households_id_fk": { + "name": "planning_settings_household_id_households_id_fk", + "tableFrom": "planning_settings", + "tableTo": "households", + "columnsFrom": [ + "household_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.task_activities": { + "name": "task_activities", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "task_id": { + "name": "task_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "actor_id": { + "name": "actor_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "fields": { + "name": "fields", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "task_activities_task_id_tasks_id_fk": { + "name": "task_activities_task_id_tasks_id_fk", + "tableFrom": "task_activities", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "task_activities_actor_id_users_id_fk": { + "name": "task_activities_actor_id_users_id_fk", + "tableFrom": "task_activities", + "tableTo": "users", + "columnsFrom": [ + "actor_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.task_assignees": { + "name": "task_assignees", + "schema": "", + "columns": { + "task_id": { + "name": "task_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "task_assignees_task_id_tasks_id_fk": { + "name": "task_assignees_task_id_tasks_id_fk", + "tableFrom": "task_assignees", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "task_assignees_user_id_users_id_fk": { + "name": "task_assignees_user_id_users_id_fk", + "tableFrom": "task_assignees", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "task_assignees_task_id_user_id_pk": { + "name": "task_assignees_task_id_user_id_pk", + "columns": [ + "task_id", + "user_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.task_entities": { + "name": "task_entities", + "schema": "", + "columns": { + "task_id": { + "name": "task_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "entity_id": { + "name": "entity_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "task_entities_task_id_tasks_id_fk": { + "name": "task_entities_task_id_tasks_id_fk", + "tableFrom": "task_entities", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "task_entities_entity_id_planning_entities_id_fk": { + "name": "task_entities_entity_id_planning_entities_id_fk", + "tableFrom": "task_entities", + "tableTo": "planning_entities", + "columnsFrom": [ + "entity_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "task_entities_task_id_entity_id_pk": { + "name": "task_entities_task_id_entity_id_pk", + "columns": [ + "task_id", + "entity_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tasks": { + "name": "tasks", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "household_id": { + "name": "household_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "status": { + "name": "status", + "type": "task_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'todo'" + }, + "planning_bucket": { + "name": "planning_bucket", + "type": "planning_bucket", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'someday'" + }, + "preceding_column": { + "name": "preceding_column", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "epic_id": { + "name": "epic_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "high": { + "name": "high", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "size": { + "name": "size", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "estimate_minutes": { + "name": "estimate_minutes", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "start_date": { + "name": "start_date", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "start_time": { + "name": "start_time", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "deadline_date": { + "name": "deadline_date", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "deadline_time": { + "name": "deadline_time", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "field_versions": { + "name": "field_versions", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "sort_order": { + "name": "sort_order", + "type": "double precision", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_by": { + "name": "created_by", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "completed_by": { + "name": "completed_by", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "trashed_at": { + "name": "trashed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "task_household_order_idx": { + "name": "task_household_order_idx", + "columns": [ + { + "expression": "household_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "sort_order", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "task_epic_idx": { + "name": "task_epic_idx", + "columns": [ + { + "expression": "epic_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "tasks_household_id_households_id_fk": { + "name": "tasks_household_id_households_id_fk", + "tableFrom": "tasks", + "tableTo": "households", + "columnsFrom": [ + "household_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tasks_epic_id_planning_entities_id_fk": { + "name": "tasks_epic_id_planning_entities_id_fk", + "tableFrom": "tasks", + "tableTo": "planning_entities", + "columnsFrom": [ + "epic_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "tasks_created_by_users_id_fk": { + "name": "tasks_created_by_users_id_fk", + "tableFrom": "tasks", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "tasks_completed_by_users_id_fk": { + "name": "tasks_completed_by_users_id_fk", + "tableFrom": "tasks", + "tableTo": "users", + "columnsFrom": [ + "completed_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.attachments": { + "name": "attachments", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "household_id": { + "name": "household_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "task_id": { + "name": "task_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "mime": { + "name": "mime", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "size": { + "name": "size", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "preview": { + "name": "preview", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "deleted": { + "name": "deleted", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "attachment_task_idx": { + "name": "attachment_task_idx", + "columns": [ + { + "expression": "task_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "attachments_household_id_households_id_fk": { + "name": "attachments_household_id_households_id_fk", + "tableFrom": "attachments", + "tableTo": "households", + "columnsFrom": [ + "household_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "attachments_task_id_tasks_id_fk": { + "name": "attachments_task_id_tasks_id_fk", + "tableFrom": "attachments", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.task_comments": { + "name": "task_comments", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "task_id": { + "name": "task_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "author_id": { + "name": "author_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "body": { + "name": "body", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "deleted": { + "name": "deleted", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "comment_task_idx": { + "name": "comment_task_idx", + "columns": [ + { + "expression": "task_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "task_comments_task_id_tasks_id_fk": { + "name": "task_comments_task_id_tasks_id_fk", + "tableFrom": "task_comments", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "task_comments_author_id_users_id_fk": { + "name": "task_comments_author_id_users_id_fk", + "tableFrom": "task_comments", + "tableTo": "users", + "columnsFrom": [ + "author_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.filter_versions": { + "name": "filter_versions", + "schema": "", + "columns": { + "filter_id": { + "name": "filter_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "author_id": { + "name": "author_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "snapshot": { + "name": "snapshot", + "type": "jsonb", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "filter_versions_filter_id_saved_filters_id_fk": { + "name": "filter_versions_filter_id_saved_filters_id_fk", + "tableFrom": "filter_versions", + "tableTo": "saved_filters", + "columnsFrom": [ + "filter_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "filter_versions_author_id_users_id_fk": { + "name": "filter_versions_author_id_users_id_fk", + "tableFrom": "filter_versions", + "tableTo": "users", + "columnsFrom": [ + "author_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "filter_versions_filter_id_version_pk": { + "name": "filter_versions_filter_id_version_pk", + "columns": [ + "filter_id", + "version" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.saved_filters": { + "name": "saved_filters", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "household_id": { + "name": "household_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "creator_id": { + "name": "creator_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "icon": { + "name": "icon", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "builtin": { + "name": "builtin", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "deleted": { + "name": "deleted", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "expression": { + "name": "expression", + "type": "jsonb", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "filter_builtin_idx": { + "name": "filter_builtin_idx", + "columns": [ + { + "expression": "household_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "builtin", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "saved_filters_household_id_households_id_fk": { + "name": "saved_filters_household_id_households_id_fk", + "tableFrom": "saved_filters", + "tableTo": "households", + "columnsFrom": [ + "household_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "saved_filters_creator_id_users_id_fk": { + "name": "saved_filters_creator_id_users_id_fk", + "tableFrom": "saved_filters", + "tableTo": "users", + "columnsFrom": [ + "creator_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.task_order_versions": { + "name": "task_order_versions", + "schema": "", + "columns": { + "household_id": { + "name": "household_id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": {}, + "foreignKeys": { + "task_order_versions_household_id_households_id_fk": { + "name": "task_order_versions_household_id_households_id_fk", + "tableFrom": "task_order_versions", + "tableTo": "households", + "columnsFrom": [ + "household_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user_view_contexts": { + "name": "user_view_contexts", + "schema": "", + "columns": { + "household_id": { + "name": "household_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "current_place_id": { + "name": "current_place_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "user_view_contexts_household_id_households_id_fk": { + "name": "user_view_contexts_household_id_households_id_fk", + "tableFrom": "user_view_contexts", + "tableTo": "households", + "columnsFrom": [ + "household_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "user_view_contexts_user_id_users_id_fk": { + "name": "user_view_contexts_user_id_users_id_fk", + "tableFrom": "user_view_contexts", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "user_view_contexts_current_place_id_planning_entities_id_fk": { + "name": "user_view_contexts_current_place_id_planning_entities_id_fk", + "tableFrom": "user_view_contexts", + "tableTo": "planning_entities", + "columnsFrom": [ + "current_place_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "user_view_contexts_household_id_user_id_pk": { + "name": "user_view_contexts_household_id_user_id_pk", + "columns": [ + "household_id", + "user_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user_view_states": { + "name": "user_view_states", + "schema": "", + "columns": { + "view_id": { + "name": "view_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "favorite": { + "name": "favorite", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "active_filters": { + "name": "active_filters", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + } + }, + "indexes": {}, + "foreignKeys": { + "user_view_states_view_id_saved_views_id_fk": { + "name": "user_view_states_view_id_saved_views_id_fk", + "tableFrom": "user_view_states", + "tableTo": "saved_views", + "columnsFrom": [ + "view_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "user_view_states_user_id_users_id_fk": { + "name": "user_view_states_user_id_users_id_fk", + "tableFrom": "user_view_states", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "user_view_states_view_id_user_id_pk": { + "name": "user_view_states_view_id_user_id_pk", + "columns": [ + "view_id", + "user_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.saved_views": { + "name": "saved_views", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "household_id": { + "name": "household_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "creator_id": { + "name": "creator_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "icon": { + "name": "icon", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "builtin": { + "name": "builtin", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "deleted": { + "name": "deleted", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "presentation": { + "name": "presentation", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expression": { + "name": "expression", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "quick_filters": { + "name": "quick_filters", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "sort": { + "name": "sort", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'manual'" + }, + "epic_lanes": { + "name": "epic_lanes", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "show_empty_lanes": { + "name": "show_empty_lanes", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "card_properties": { + "name": "card_properties", + "type": "jsonb", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "view_builtin_idx": { + "name": "view_builtin_idx", + "columns": [ + { + "expression": "household_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "builtin", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "saved_views_household_id_households_id_fk": { + "name": "saved_views_household_id_households_id_fk", + "tableFrom": "saved_views", + "tableTo": "households", + "columnsFrom": [ + "household_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "saved_views_creator_id_users_id_fk": { + "name": "saved_views_creator_id_users_id_fk", + "tableFrom": "saved_views", + "tableTo": "users", + "columnsFrom": [ + "creator_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": { + "public.household_role": { + "name": "household_role", + "schema": "public", + "values": [ + "admin", + "member" + ] + }, + "public.token_purpose": { + "name": "token_purpose", + "schema": "public", + "values": [ + "bootstrap", + "invite", + "recovery", + "verify_email" + ] + }, + "public.planning_bucket": { + "name": "planning_bucket", + "schema": "public", + "values": [ + "someday", + "within_year", + "within_month", + "ready" + ] + }, + "public.entity_kind": { + "name": "entity_kind", + "schema": "public", + "values": [ + "epic", + "place", + "resource", + "tag" + ] + }, + "public.task_status": { + "name": "task_status", + "schema": "public", + "values": [ + "todo", + "in_progress", + "done" + ] + } + }, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/apps/api/drizzle/meta/_journal.json b/apps/api/drizzle/meta/_journal.json index 8bbb1b8..948d6a3 100644 --- a/apps/api/drizzle/meta/_journal.json +++ b/apps/api/drizzle/meta/_journal.json @@ -29,6 +29,20 @@ "when": 1791993728147, "tag": "0003_easy_elektra", "breakpoints": true + }, + { + "idx": 4, + "version": "7", + "when": 1793549688066, + "tag": "0004_eager_ulik", + "breakpoints": true + }, + { + "idx": 5, + "version": "7", + "when": 1793554120517, + "tag": "0005_jazzy_blue_shield", + "breakpoints": true } ] } \ No newline at end of file diff --git a/apps/api/package.json b/apps/api/package.json index 7993a7c..660a708 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -15,6 +15,7 @@ }, "dependencies": { "@fastify/cookie": "11.1.3", + "@fastify/multipart": "10.1.6", "@fastify/rate-limit": "11.2.1", "@fastify/swagger": "9.9.2", "@fastify/websocket": "11.3.4", @@ -24,10 +25,13 @@ "drizzle-orm": "0.45.4", "fastify": "5.12.7", "fastify-type-provider-zod": "6.1.0", + "file-type": "22.3.0", + "heic-convert": "2.1.0", "nodemailer": "10.1.0", "pg": "8.23.1", "pg-boss": "12.37.1", "pino": "10.4.0", + "sharp": "0.35.5", "zod": "4.6.7" }, "exports": { diff --git a/apps/api/src/accounts/routes.ts b/apps/api/src/accounts/routes.ts index e203299..9e0247b 100644 --- a/apps/api/src/accounts/routes.ts +++ b/apps/api/src/accounts/routes.ts @@ -1,3 +1,4 @@ +import { registerHouseholdEvents } from '../collaboration/events.js'; import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify'; import type { ZodTypeProvider } from 'fastify-type-provider-zod'; import cookie from '@fastify/cookie'; @@ -6,12 +7,12 @@ import websocket from '@fastify/websocket'; import { z } from 'zod'; import { and, eq, gt } from 'drizzle-orm'; import type { RegistrationResponseJSON, AuthenticationResponseJSON } from '@simplewebauthn/server'; -import { emailSchema, errorSchema, nameSchema, okSchema, registrationInput, roleSchema, sessionSchema, smtpSchema, verificationInput } from '@tendly/shared'; +import { emailSchema, errorSchema, nameSchema, timezoneSchema, okSchema, registrationInput, roleSchema, sessionSchema, smtpSchema, verificationInput } from '@tendly/shared'; import { AccountService } from './service.js'; import { MailService } from './mail.js'; import { AccountError } from './errors.js'; import { accountView, deploymentAdmin, householdAccess, lockAccounts, recent, signedIn } from './access.js'; -import { credentials, memberships, securityEvents, sessions, tokens, users } from './schema.js'; +import { credentials, households, memberships, securityEvents, sessions, tokens, users } from './schema.js'; import { digest, randomToken } from './crypto.js'; const ok = { ok: true as const }; @@ -47,12 +48,13 @@ export async function registerAccountRoutes(server: FastifyInstance, service: Ac reply.header('Referrer-Policy', 'no-referrer'); if (!['GET', 'HEAD', 'OPTIONS'].includes(request.method)) { if (request.headers.origin !== service.origin) throw new AccountError('invalid_origin', 403); - if (!request.headers['content-type']?.startsWith('application/json')) throw new AccountError('json_required', 415); + if (!(request.routeOptions.config.fileUpload && request.headers['content-type']?.startsWith('multipart/form-data;')) && !request.headers['content-type']?.startsWith('application/json')) throw new AccountError('json_required', 415); } }); app.setErrorHandler((error, request, reply) => { if (error instanceof AccountError) return reply.code(error.statusCode).send({ error: error.code }); if (error && typeof error === 'object' && 'validation' in error && error.validation) return reply.code(400).send({ error: 'invalid_input' }); + if (error && typeof error === 'object' && 'statusCode' in error && error.statusCode === 413) return reply.code(413).send({ error: 'file_too_large' }); if (error && typeof error === 'object' && 'statusCode' in error && error.statusCode === 429) return reply.code(429).send({ error: 'too_many_requests' }); request.log.error({ code: 'account_operation_failed' }, 'Account operation failed'); return reply.code(500).send({ error: 'operation_failed' }); @@ -71,9 +73,20 @@ export async function registerAccountRoutes(server: FastifyInstance, service: Ac }; app.addHook('onRoute', (route) => { route.schema ??= {}; - route.schema.response = { 400: errorSchema, 401: errorSchema, 403: errorSchema, 404: errorSchema, 409: errorSchema, 429: errorSchema, 500: errorSchema, 503: errorSchema, ...(typeof route.schema.response === 'object' ? route.schema.response : {}) }; + route.schema.response = { 400: errorSchema, 401: errorSchema, 403: errorSchema, 404: errorSchema, 409: errorSchema, 413:errorSchema,415:errorSchema, 429: errorSchema, 500: errorSchema, 503: errorSchema, ...(typeof route.schema.response === 'object' ? route.schema.response : {}) }; }); const authLimit = { rateLimit: { max: 20, timeWindow: '1 minute' } }; + app.patch('/api/v1/households/:id', { schema: { params: idParam, body: z.object({ baseName:z.string(),baseTimezone:z.string(),name:nameSchema,timezone:timezoneSchema }),response:{200:okSchema} } },async request=>{ + const current=await actor(request);signedIn(current); + await db.transaction(async tx=>{ + await householdAccess(tx,current,request.params.id,true); + const [home]=await tx.select().from(households).where(eq(households.id,request.params.id)).for('update'); + await householdAccess(tx,current,request.params.id,true); + if(!home || home.name!==request.body.baseName || home.timezone!==request.body.baseTimezone)throw new AccountError('household_conflict',409); + await tx.update(households).set({name:request.body.name,timezone:request.body.timezone}).where(eq(households.id,home.id)); + }); + return ok; + }); app.get('/api/v1/auth/status', { schema: { response: { 200: z.object({ initialized: z.boolean(), emailAvailable: z.boolean() }) } } }, async () => ({ initialized: await service.initialized(), emailAvailable: !!(await mail.config()) })); app.get('/api/v1/auth/session', { schema: { response: { 200: sessionSchema } } }, async (request) => { const current = await actor(request); @@ -218,18 +231,6 @@ export async function registerAccountRoutes(server: FastifyInstance, service: Ac }); // Authorization happens before upgrade and again while the socket is alive. // Future broadcasts must recheck membership before sending household content. - app.get('/api/v1/households/:id/events', { - websocket: true, schema: { params: idParam, hide: true }, - preValidation: async (request) => { - if (request.headers.origin !== service.origin) throw new AccountError('invalid_origin', 403); - await householdAccess(db, await actor(request), request.params.id); - }, - }, (socket, request) => { - const timer = setInterval(() => { - void actor(request).then((current) => householdAccess(db, current, request.params.id)).catch(() => socket.close(1008, 'Access revoked')); - }, 15_000); - socket.on('close', () => clearInterval(timer)); - socket.on('error', () => clearInterval(timer)); - }); + registerHouseholdEvents(app, service, sessionName); } diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 11a8dd2..888d635 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -1,3 +1,5 @@ +import { registerViewRoutes } from './views/routes.js'; +import { registerContentRoutes } from './content/routes.js'; import { registerTaskRoutes } from './tasks/routes.js'; import { registerAccountRoutes } from './accounts/routes.js'; import type { AccountService } from './accounts/service.js'; @@ -9,6 +11,8 @@ import { healthSchema, versionSchema } from '@tendly/shared'; import { logRedaction } from './logging.js'; interface AppOptions { + attachmentRoot?: string; + attachmentLimit?: number; accounts?: { service: AccountService; mail: MailService }; checkDatabase: () => Promise; closeDatabase?: () => Promise; @@ -22,7 +26,14 @@ export async function buildApp(options: AppOptions) { app.setSerializerCompiler(serializerCompiler); await app.register(swagger, { openapi: { info: { title: 'Tendly API', version: options.version ?? '0.0.0-dev' } }, - transform: jsonSchemaTransform, + transform: input=>{ + const transformed=jsonSchemaTransform(input); + if(input.route.config?.fileUpload) { + transformed.schema.consumes=['multipart/form-data']; + transformed.schema.body={type:'object',required:['file'],properties:{file:{type:'string',format:'binary'}}}; + } + return transformed; + }, }); // Do not log URL query strings: later recovery links carry single-use secrets. app.addHook('onResponse', async (request, reply) => { @@ -41,6 +52,8 @@ export async function buildApp(options: AppOptions) { if (options.accounts) { await registerAccountRoutes(app, options.accounts.service, options.accounts.mail); await registerTaskRoutes(app, options.accounts.service); + await registerViewRoutes(app, options.accounts.service); + await registerContentRoutes(app, options.accounts.service, options.attachmentRoot ?? '/data/attachments', options.attachmentLimit ?? 50_000_000); } await app.ready(); return app; diff --git a/apps/api/src/collaboration/events.ts b/apps/api/src/collaboration/events.ts new file mode 100644 index 0000000..7c6c39f --- /dev/null +++ b/apps/api/src/collaboration/events.ts @@ -0,0 +1,142 @@ +import { eq } from 'drizzle-orm'; +import { memberships } from '../accounts/schema.js'; +import type { FastifyInstance } from 'fastify'; +import type { ZodTypeProvider } from 'fastify-type-provider-zod'; +import type { WebSocket } from 'ws'; +import { z } from 'zod'; +import { householdAccess } from '../accounts/access.js'; +import { AccountError } from '../accounts/errors.js'; +import type { AccountService } from '../accounts/service.js'; + +export function registerHouseholdEvents( + server: FastifyInstance, + accounts: AccountService, + cookie: string, +) { + const app = server.withTypeProvider(); + const subscribers = new Set<{ + householdId: string; + notify: (resource?: string) => void; + socket: WebSocket; + }>(); + // REST handlers finish their transactions before responding. No draft or rolled-back + // state is broadcast, and clients always fetch authoritative data with their own access. + app.addHook('onResponse', async (request, reply) => { + if (['GET', 'HEAD', 'OPTIONS'].includes(request.method) || reply.statusCode >= 400) return; + const householdId = /^\/api\/v1\/households\/([0-9a-f-]{36})(?:\/|$)/i.exec(request.url)?.[1]; + if (!householdId) { + const path = request.url.split('?')[0]; + if ( + ![ + '/api/v1/account', + '/api/v1/auth/invitations/accept', + '/api/v1/auth/register/verify', + ].includes(path ?? '') + ) + return; + const setCookie = reply.getHeader('set-cookie'); + const values = Array.isArray(setCookie) ? setCookie : [String(setCookie ?? '')]; + const issued = values.find((value) => String(value).startsWith(cookie + '=')); + const bearer = issued + ? String(issued) + .split(';')[0]! + .slice(cookie.length + 1) + : request.cookies[cookie]; + const current = await accounts.findSession(bearer); + if (!current) return; + const homes = await accounts.db + .select({ id: memberships.householdId }) + .from(memberships) + .where(eq(memberships.userId, current.user.id)); + for (const subscriber of subscribers) + if (homes.some((home) => home.id === subscriber.householdId)) subscriber.notify('members'); + return; + } + // These POST endpoints are read-only queries, not mutations. Broadcasting them + // would make subscribed previews invalidate and refetch themselves indefinitely. + if (/\/(task-query|search)(?:\?|$)/.test(request.url)) return; + const parts = request.url.split('?')[0]!.split('/').filter(Boolean); + const resource = + parts[6] === 'comments' + ? 'comments' + : parts[6] === 'attachments' + ? 'attachments' + : (parts[4] ?? 'all'); + for (const subscriber of subscribers) + if (subscriber.householdId === householdId) subscriber.notify(resource); + }); + app.addHook('preClose', async () => { + for (const subscriber of subscribers) subscriber.socket.close(1001, 'Server shutting down'); + }); + app.get( + '/api/v1/households/:id/events', + { + websocket: true, + schema: { params: z.object({ id: z.uuid() }), hide: true }, + preValidation: async (request) => { + if (request.headers.origin !== accounts.origin) + throw new AccountError('invalid_origin', 403); + await householdAccess( + accounts.db, + await accounts.findSession(request.cookies[cookie]), + request.params.id, + ); + }, + }, + (socket, request) => { + let closed = false, + checking = false; + const pending = new Set(); + const validate = async (send: boolean) => { + if (closed) return; + if (checking) { + return; + } + checking = true; + try { + // Never reuse the HTTP request's cached actor: sessions and memberships can + // be revoked while a socket remains open, including via CLI recovery. + await householdAccess( + accounts.db, + await accounts.findSession(request.cookies[cookie]), + request.params.id, + ); + if (send && !closed && socket.readyState === 1) { + const resources = [...pending]; + pending.clear(); + socket.send(JSON.stringify({ type: 'invalidate', resources })); + } + } catch { + socket.close(1008, 'Access revoked'); + } finally { + checking = false; + if (pending.size && !closed && socket.readyState === 1) { + void validate(true); + } + } + }; + const subscriber = { + householdId: request.params.id, + socket, + notify: (resource = 'all') => { + pending.add(resource); + void validate(true); + }, + }; + subscribers.add(subscriber); + const timer = setInterval(() => { + void validate(false); + }, 15_000); + timer.unref(); + const cleanup = () => { + closed = true; + clearInterval(timer); + subscribers.delete(subscriber); + }; + socket.on('close', cleanup); + socket.on('error', cleanup); + // Cover mutations between the initial REST read and subscription establishment. + subscriber.notify(); + }, + ); +} diff --git a/apps/api/src/config.ts b/apps/api/src/config.ts index e0c8022..694d6fa 100644 --- a/apps/api/src/config.ts +++ b/apps/api/src/config.ts @@ -8,6 +8,8 @@ const schema = z.object({ const url = new URL(value); return !url.username && !url.password && url.pathname === '/' && !url.search && !url.hash; }, 'Expected an origin without credentials, path, query, or fragment'), + ATTACHMENT_MAX_BYTES: z.coerce.number().int().positive().max(1_000_000_000).default(50_000_000), + ATTACHMENT_ROOT: z.string().default('/data/attachments'), PORT: z.coerce.number().int().min(1).max(65535).default(3000), HOST: z.string().default('0.0.0.0'), LOG_LEVEL: z.enum(['fatal', 'error', 'warn', 'info', 'debug', 'trace', 'silent']).default('info'), diff --git a/apps/api/src/content/files.ts b/apps/api/src/content/files.ts new file mode 100644 index 0000000..7973ec7 --- /dev/null +++ b/apps/api/src/content/files.ts @@ -0,0 +1,121 @@ +import { eq } from 'drizzle-orm'; +import { randomUUID } from 'node:crypto'; +import { mkdir, rm, stat, readdir } from 'node:fs/promises'; +import { createWriteStream } from 'node:fs'; +import { pipeline } from 'node:stream/promises'; +import { join } from 'node:path'; +import { execFile } from 'node:child_process'; +import { promisify } from 'node:util'; +import { fileURLToPath } from 'node:url'; +import { fileTypeFromFile } from 'file-type'; +import type { MultipartFile } from '@fastify/multipart'; +import type { Actor } from '../accounts/access.js'; +import { attachments } from './schema.js'; +import { ContentService } from './service.js'; +import { AccountError } from '../accounts/errors.js'; +const exec = promisify(execFile); +export class FileStore { + private active = 0; + constructor( + readonly service: ContentService, + readonly root: string, + ) {} + path(id: string, preview = false, thumbnail = false) { + return join(this.root, id + (thumbnail ? '.thumb.jpg' : preview ? '.jpg' : '.original')); + } + async cleanupOrphans() { + await mkdir(this.root, { recursive: true }); + for (const name of await readdir(this.root)) { + const match = /^([0-9a-f-]{36})\.(original|jpg|thumb\.jpg)$/.exec(name); + if (!match) continue; + const path = join(this.root, name); + const info = await stat(path).catch(() => null); + // Fresh uploads may not have committed metadata yet. Never sweep recent files. + if (!info || Date.now() - info.mtimeMs < 24 * 3600_000) continue; + const [record] = await this.service.db + .select({ id: attachments.id }) + .from(attachments) + .where(eq(attachments.id, match[1]!)); + if (!record) await rm(path, { force: true }); + } + } + async upload(actor: Actor, householdId: string, taskId: string, part: MultipartFile) { + await this.service.task(actor, householdId, taskId); + if (this.active >= 2) { + part.file.resume(); + throw new AccountError('uploads_busy', 503); + } + this.active++; + const id = randomUUID(); + try { + await mkdir(this.root, { recursive: true }); + await pipeline(part.file, createWriteStream(this.path(id), { flags: 'wx', mode: 0o600 })); + if (part.file.truncated) throw new AccountError('file_too_large', 413); + const size = (await stat(this.path(id))).size; + if (!size) throw new AccountError('empty_file'); + const type = await fileTypeFromFile(this.path(id)); + const mime = type?.mime ?? 'application/octet-stream'; + const heic = ['heic', 'heif'].includes(type?.ext ?? ''); + if (mime.startsWith('video/')) throw new AccountError('video_not_supported'); + const image = + heic || ['image/jpeg', 'image/png', 'image/webp', 'image/gif', 'image/avif'].includes(mime); + if (image) { + try { + await exec( + process.execPath, + [ + '--max-old-space-size=256', + ...(import.meta.url.endsWith('.ts') ? ['--import', import.meta.resolve('tsx')] : []), + fileURLToPath( + new URL( + import.meta.url.endsWith('.ts') ? './preview-worker.ts' : './preview-worker.js', + import.meta.url, + ), + ), + this.path(id), + this.path(id, true), + heic ? 'heic' : 'image', + ], + { timeout: 30_000, maxBuffer: 1024 * 64 }, + ); + } catch { + throw new AccountError('image_preview_failed'); + } + } + return await this.service.db.transaction(async (tx) => { + const home = await this.service.tasks.scope(tx, actor, householdId, true); + await this.service.tasks.get(tx, householdId, taskId, home.timezone); + const [row] = await tx + .insert(attachments) + .values({ + id, + householdId, + taskId, + name: + Array.from(part.filename) + .map((c) => + c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127 || c === '/' || c === '\\' + ? '_' + : c, + ) + .join('') + .slice(0, 255) || 'file', + mime, + size, + preview: image, + }) + .returning(); + return { ...row!, createdAt: row!.createdAt.toISOString() }; + }); + } catch (error) { + await Promise.all([ + rm(this.path(id), { force: true }), + rm(this.path(id, true), { force: true }), + rm(this.path(id, true, true), { force: true }), + ]); + throw error; + } finally { + this.active--; + } + } +} diff --git a/apps/api/src/content/heic-convert.d.ts b/apps/api/src/content/heic-convert.d.ts new file mode 100644 index 0000000..34018af --- /dev/null +++ b/apps/api/src/content/heic-convert.d.ts @@ -0,0 +1,8 @@ +declare module 'heic-convert' { + const convert: (options: { + buffer: Uint8Array; + format: 'JPEG'; + quality: number; + }) => Promise; + export default convert; +} diff --git a/apps/api/src/content/preview-worker.ts b/apps/api/src/content/preview-worker.ts new file mode 100644 index 0000000..fb196b6 --- /dev/null +++ b/apps/api/src/content/preview-worker.ts @@ -0,0 +1,33 @@ +import { readFile, writeFile } from 'node:fs/promises'; +import sharp from 'sharp'; +import convert from 'heic-convert'; +const [source, destination, kind] = process.argv.slice(2); +if (!source || !destination) throw new Error('Missing preview paths'); +const input = + kind === 'heic' + ? Buffer.from( + await convert({ + buffer: await readFile(source), + format: 'JPEG', + quality: 0.9, + }), + ) + : source; +const preview = await sharp(input, { limitInputPixels: 60_000_000 }) + .rotate() + .jpeg({ quality: 90 }) + .toBuffer(); +await writeFile(destination, preview, { flag: 'wx' }); +await writeFile( + destination.replace(/\.jpg$/, '.thumb.jpg'), + await sharp(preview) + .resize({ + width: 400, + height: 400, + fit: 'inside', + withoutEnlargement: true, + }) + .jpeg({ quality: 80 }) + .toBuffer(), + { flag: 'wx' }, +); diff --git a/apps/api/src/content/references.ts b/apps/api/src/content/references.ts new file mode 100644 index 0000000..c17fc3a --- /dev/null +++ b/apps/api/src/content/references.ts @@ -0,0 +1,61 @@ +import { and, eq } from 'drizzle-orm'; +import { toDocument, type ContentNode } from '@tendly/shared'; +import type { QueryDatabase } from '../accounts/database.js'; +import { memberships } from '../accounts/schema.js'; +import { attachments } from './schema.js'; +import { AccountError } from '../accounts/errors.js'; +export async function validateReferences( + db: QueryDatabase, + householdId: string, + taskId: string | undefined, + value: unknown, + previous?: unknown, +) { + const priorMentions = new Set(); + const collect = (n: ContentNode) => { + if (n.type === 'mention') priorMentions.add(String(n.attrs?.id)); + for (const c of n.content ?? []) collect(c); + }; + if (previous) collect(toDocument(previous)); + const visit = async (node: ContentNode): Promise => { + if (node.type === 'mention' && !priorMentions.has(String(node.attrs?.id))) { + const [member] = await db + .select() + .from(memberships) + .where( + and( + eq(memberships.householdId, householdId), + eq(memberships.userId, String(node.attrs?.id)), + ), + ); + if (!member) throw new AccountError('invalid_task_reference'); + } + for (const url of [ + node.type === 'image' ? node.attrs?.src : undefined, + ...(node.marks ?? []).filter((m) => m.type === 'link').map((m) => m.attrs?.href), + ]) { + if (typeof url !== 'string' || !url.startsWith('/api/')) continue; + const match = + /^\/api\/v1\/households\/([0-9a-f-]{36})\/attachments\/([0-9a-f-]{36})\/(preview|download)$/.exec( + url, + ); + if (!match || match[1] !== householdId || !taskId) + throw new AccountError('invalid_task_reference'); + const [file] = await db + .select() + .from(attachments) + .where( + and( + eq(attachments.id, match[2]!), + eq(attachments.householdId, householdId), + eq(attachments.taskId, taskId), + eq(attachments.deleted, false), + ), + ); + if (!file || (node.type === 'image' && !file.preview)) + throw new AccountError('invalid_task_reference'); + } + for (const child of node.content ?? []) await visit(child); + }; + await visit(toDocument(value)); +} diff --git a/apps/api/src/content/routes.ts b/apps/api/src/content/routes.ts new file mode 100644 index 0000000..1e33c96 --- /dev/null +++ b/apps/api/src/content/routes.ts @@ -0,0 +1,235 @@ +import { createReadStream } from 'node:fs'; +import { stat } from 'node:fs/promises'; +import multipart from '@fastify/multipart'; +import type { FastifyInstance, FastifyRequest } from 'fastify'; +import type { ZodTypeProvider } from 'fastify-type-provider-zod'; +import { z } from 'zod'; +import { + commentSchema, + commentWriteSchema, + commentPatchSchema, + attachmentSchema, + activitySchema, + searchHitSchema, +} from '@tendly/shared'; +import { ContentService } from './service.js'; +import { FileStore } from './files.js'; +import type { AccountService } from '../accounts/service.js'; +import { signedIn } from '../accounts/access.js'; +import { AccountError } from '../accounts/errors.js'; +const home = z.object({ householdId: z.uuid() }); +const task = home.extend({ taskId: z.uuid() }); +const paging = z.object({ offset: z.coerce.number().int().min(0).default(0) }); +export async function registerContentRoutes( + server: FastifyInstance, + accounts: AccountService, + root: string, + limit: number, +) { + const app = server.withTypeProvider(); + const service = new ContentService(accounts.db), + files = new FileStore(service, root); + await app.register(multipart, { + limits: { fileSize: limit, files: 1, fields: 0, parts: 1 }, + }); + let cleaning = false; + const sweep = () => { + if (cleaning) return; + cleaning = true; + void files + .cleanupOrphans() + .catch(() => app.log.error('Attachment cleanup failed')) + .finally(() => { + cleaning = false; + }); + }; + const cleanup = setInterval(sweep, 3600_000); + cleanup.unref(); + app.addHook('onClose', async () => { + clearInterval(cleanup); + }); + const cookie = accounts.origin.startsWith('https:') ? '__Host-tendly' : 'tendly_session'; + const actor = async (r: FastifyRequest) => { + const a = await accounts.findSession(r.cookies[cookie]); + signedIn(a); + return a; + }; + app.get( + '/api/v1/households/:householdId/upload-policy', + { + schema: { + params: home, + response: { 200: z.object({ maxBytes: z.number() }) }, + }, + }, + async (r) => { + await service.tasks.scope(service.db, await actor(r), r.params.householdId); + return { maxBytes: limit }; + }, + ); + app.get( + '/api/v1/households/:householdId/tasks/:taskId/comments', + { + schema: { + params: task, + querystring: paging, + response: { + 200: z.object({ + items: z.array(commentSchema), + nextOffset: z.number().nullable(), + }), + }, + }, + }, + async (r) => + service.listComments(await actor(r), r.params.householdId, r.params.taskId, r.query.offset), + ); + app.post( + '/api/v1/households/:householdId/tasks/:taskId/comments', + { + schema: { + params: task, + body: commentWriteSchema, + response: { 200: commentSchema }, + }, + }, + async (r) => + service.writeComment(await actor(r), r.params.householdId, r.params.taskId, r.body), + ); + app.patch( + '/api/v1/households/:householdId/tasks/:taskId/comments/:id', + { + schema: { + params: task.extend({ id: z.uuid() }), + body: commentPatchSchema, + response: { 200: commentSchema }, + }, + }, + async (r) => + service.writeComment( + await actor(r), + r.params.householdId, + r.params.taskId, + r.body, + r.params.id, + ), + ); + app.get( + '/api/v1/households/:householdId/tasks/:taskId/activity', + { + schema: { + params: task, + querystring: paging, + response: { + 200: z.object({ + items: z.array(activitySchema), + nextOffset: z.number().nullable(), + }), + }, + }, + }, + async (r) => + service.activity(await actor(r), r.params.householdId, r.params.taskId, r.query.offset), + ); + app.get( + '/api/v1/households/:householdId/tasks/:taskId/attachments', + { schema: { params: task, response: { 200: z.array(attachmentSchema) } } }, + async (r) => service.files(await actor(r), r.params.householdId, r.params.taskId), + ); + app.post( + '/api/v1/households/:householdId/tasks/:taskId/attachments', + { + config: { fileUpload: true }, + schema: { params: task, response: { 200: attachmentSchema } }, + preHandler: async (r) => { + await service.task(await actor(r), r.params.householdId, r.params.taskId); + }, + }, + async (r) => { + const part = await r.file(); + if (!part) throw new AccountError('empty_file'); + return files.upload(await actor(r), r.params.householdId, r.params.taskId, part); + }, + ); + for (const mode of ['download', 'preview', 'thumbnail'] as const) { + app.get( + `/api/v1/households/:householdId/attachments/:id/${mode}`, + { schema: { params: home.extend({ id: z.uuid() }) } }, + async (r, reply) => { + const file = await service.file(await actor(r), r.params.householdId, r.params.id); + if ( + mode !== 'download' && + !file.preview && + (file.mime !== 'application/pdf' || mode === 'thumbnail') + ) + throw new AccountError('preview_unavailable', 404); + const path = files.path(file.id, mode !== 'download' && file.preview, mode === 'thumbnail'); + try { + await stat(path); + } catch { + throw new AccountError('file_not_found', 404); + } + reply + .header('X-Content-Type-Options', 'nosniff') + .header('Cache-Control', 'private, no-store'); + reply.header('Content-Security-Policy', "default-src 'none'; sandbox"); + reply.header( + 'Content-Disposition', + `${mode === 'download' ? 'attachment' : 'inline'}; filename*=UTF-8''${encodeURIComponent(file.name).replace(/'/g, '%27')}`, + ); + return reply + .type(mode !== 'download' && file.preview ? 'image/jpeg' : file.mime) + .send(createReadStream(path)); + }, + ); + } + app.post( + '/api/v1/households/:householdId/search', + { + schema: { + params: home, + body: paging.extend({ + q: z.string().trim().min(1).max(200), + filterIds: z.array(z.uuid()).max(50).default([]), + }), + response: { + 200: z.object({ + items: z.array(searchHitSchema), + nextOffset: z.number().nullable(), + warnings: z.array(z.string()), + }), + }, + }, + }, + async (r) => + service.search( + await actor(r), + r.params.householdId, + r.body.q, + r.body.offset, + r.body.filterIds, + ), + ); + app.get( + '/api/v1/households/:householdId/search', + { + schema: { + params: home, + querystring: paging.extend({ q: z.string().trim().min(1).max(200) }), + response: { + 200: z.object({ + items: z.array(searchHitSchema), + nextOffset: z.number().nullable(), + warnings: z.array(z.string()), + }), + }, + }, + }, + async (r) => service.search(await actor(r), r.params.householdId, r.query.q, r.query.offset), + ); +} +declare module 'fastify' { + interface FastifyContextConfig { + fileUpload?: boolean; + } +} diff --git a/apps/api/src/content/schema.ts b/apps/api/src/content/schema.ts new file mode 100644 index 0000000..668a857 --- /dev/null +++ b/apps/api/src/content/schema.ts @@ -0,0 +1,51 @@ +import { + pgTable, + uuid, + text, + integer, + boolean, + timestamp, + jsonb, + index, +} from 'drizzle-orm/pg-core'; +import { tasks } from '../tasks/schema.js'; +import { households, users } from '../accounts/schema.js'; +import type { Document } from '@tendly/shared'; +export const comments = pgTable( + 'task_comments', + { + id: uuid('id').primaryKey().defaultRandom(), + taskId: uuid('task_id') + .notNull() + .references(() => tasks.id, { onDelete: 'cascade' }), + authorId: uuid('author_id').references(() => users.id, { + onDelete: 'set null', + }), + body: jsonb('body').$type().notNull(), + version: integer('version').notNull().default(1), + deleted: boolean('deleted').notNull().default(false), + createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(), + }, + (t) => [index('comment_task_idx').on(t.taskId, t.createdAt)], +); +export const attachments = pgTable( + 'attachments', + { + id: uuid('id').primaryKey(), + householdId: uuid('household_id') + .notNull() + .references(() => households.id, { onDelete: 'cascade' }), + taskId: uuid('task_id') + .notNull() + .references(() => tasks.id, { onDelete: 'cascade' }), + name: text('name').notNull(), + mime: text('mime').notNull(), + size: integer('size').notNull(), + preview: boolean('preview').notNull().default(false), + version: integer('version').notNull().default(1), + deleted: boolean('deleted').notNull().default(false), + createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(), + }, + (t) => [index('attachment_task_idx').on(t.taskId)], +); diff --git a/apps/api/src/content/search.ts b/apps/api/src/content/search.ts new file mode 100644 index 0000000..0b6fc84 --- /dev/null +++ b/apps/api/src/content/search.ts @@ -0,0 +1,79 @@ +import { sql, type SQL } from 'drizzle-orm'; +import { plainText, searchHitSchema } from '@tendly/shared'; +import type { z } from 'zod'; +import type { Actor } from '../accounts/access.js'; +import type { Database } from '../accounts/database.js'; +import { TaskService } from '../tasks/service.js'; +import { ViewService } from '../views/service.js'; +import { tasks, entities } from '../tasks/schema.js'; +import { comments } from './schema.js'; + +export async function searchContent( + db: Database, + actor: Actor, + householdId: string, + q: string, + offset: number, + filterIds: string[], +) { + return db.transaction( + async (tx) => { + await new TaskService(db).scope(tx, actor, householdId); + // Read definitions, effective task values and content in the same snapshot. + const filtered = filterIds.length + ? await new ViewService(db).queryWithin( + tx, + actor, + householdId, + { filterIds, offset: 0, limit: Number.MAX_SAFE_INTEGER }, + true, + ) + : null; + const warnings = filtered?.warnings ?? []; + const items: z.infer[] = []; + if (warnings.length) return { items, nextOffset: null, warnings }; + const ids = filtered?.items.map((t) => t.id) ?? []; + const restrict = (id: SQL) => + filtered + ? sql` AND ${id} IN (SELECT jsonb_array_elements_text(${JSON.stringify(ids)}::jsonb)::uuid)` + : sql``; + const needle = q.toLowerCase(); + let scanned = 0, + matched = 0; + while (items.length < 51) { + const batch = await tx.execute(sql` + SELECT * FROM ( + SELECT id, 'task' as kind, title, description as body, id as "taskId" + FROM ${tasks} WHERE household_id=${householdId} AND trashed_at IS NULL ${restrict(sql`id`)} + UNION ALL + SELECT c.id, 'comment', t.title, c.body, t.id FROM ${comments} c JOIN ${tasks} t ON t.id=c.task_id + WHERE t.household_id=${householdId} AND t.trashed_at IS NULL AND NOT c.deleted ${restrict(sql`t.id`)} + UNION ALL + SELECT id, kind::text, name, to_jsonb(description), NULL::uuid FROM ${entities} + WHERE household_id=${householdId} AND kind IN ('epic','tag') AND ${!filtered} + ) hits ORDER BY title,id,kind LIMIT 256 OFFSET ${scanned}`); + for (const row of batch.rows) { + // Inline marks split text nodes without inserting spaces. Reuse the exact + // projection used by description filters rather than joining JSONPath leaves. + const text = plainText(row.body ?? ''); + if ( + !text.toLowerCase().includes(needle) && + (row.kind === 'comment' || !String(row.title).toLowerCase().includes(needle)) + ) + continue; + if (matched++ >= offset) + items.push(searchHitSchema.parse({ ...row, snippet: text.slice(0, 250) })); + if (items.length === 51) break; + } + if (batch.rows.length < 256) break; + scanned += batch.rows.length; + } + return { + items: items.slice(0, 50), + nextOffset: items.length > 50 ? offset + 50 : null, + warnings, + }; + }, + { isolationLevel: 'repeatable read', accessMode: 'read only' }, + ); +} diff --git a/apps/api/src/content/service.ts b/apps/api/src/content/service.ts new file mode 100644 index 0000000..76c6743 --- /dev/null +++ b/apps/api/src/content/service.ts @@ -0,0 +1,166 @@ +import { searchContent } from './search.js'; +import { and, eq, desc, isNull } from 'drizzle-orm'; +import { plainText, toDocument } from '@tendly/shared'; +import type { Actor } from '../accounts/access.js'; +import type { Database } from '../accounts/database.js'; +import { users } from '../accounts/schema.js'; +import { TaskService } from '../tasks/service.js'; +import { tasks, taskActivities } from '../tasks/schema.js'; +import { comments, attachments } from './schema.js'; +import { AccountError } from '../accounts/errors.js'; +import { validateReferences } from './references.js'; +export class ContentService { + readonly tasks: TaskService; + constructor(readonly db: Database) { + this.tasks = new TaskService(db); + } + async task(actor: Actor, householdId: string, taskId: string) { + const home = await this.tasks.scope(this.db, actor, householdId); + return this.tasks.get(this.db, householdId, taskId, home.timezone); + } + async listComments(actor: Actor, householdId: string, taskId: string, offset: number) { + await this.task(actor, householdId, taskId); + const rows = await this.db + .select({ comment: comments, author: users.name }) + .from(comments) + .leftJoin(users, eq(users.id, comments.authorId)) + .where(and(eq(comments.taskId, taskId), eq(comments.deleted, false))) + .orderBy(desc(comments.createdAt), desc(comments.id)) + .offset(offset) + .limit(51); + return { + items: rows.slice(0, 50).map(({ comment: c, author }) => ({ + ...c, + author: author ?? '—', + createdAt: c.createdAt.toISOString(), + updatedAt: c.updatedAt.toISOString(), + })), + nextOffset: rows.length > 50 ? offset + 50 : null, + }; + } + async writeComment( + actor: Actor, + householdId: string, + taskId: string, + input: { + body?: unknown; + deleted?: boolean | undefined; + baseVersion?: number | undefined; + }, + id?: string, + ) { + return this.db.transaction(async (tx) => { + const home = await this.tasks.scope(tx, actor, householdId, true); + await this.tasks.get(tx, householdId, taskId, home.timezone); + if (input.body) { + if (!plainText(input.body).trim() && !JSON.stringify(input.body).includes('"image"')) + throw new AccountError('empty_comment'); + if (!id) await validateReferences(tx, householdId, taskId, input.body); + } + let row; + if (id) { + const [old] = await tx + .select() + .from(comments) + .where(and(eq(comments.id, id), eq(comments.taskId, taskId))) + .for('update'); + if (!old) throw new AccountError('comment_not_found', 404); + if (input.body) await validateReferences(tx, householdId, taskId, input.body, old.body); + if (old.authorId !== actor.user.id) throw new AccountError('comment_author_required', 403); + if (old.version !== input.baseVersion) throw new AccountError('comment_conflict', 409); + [row] = await tx + .update(comments) + .set({ + ...(input.body ? { body: toDocument(input.body) } : {}), + ...(input.deleted !== undefined ? { deleted: input.deleted } : {}), + version: old.version + 1, + updatedAt: new Date(), + }) + .where(eq(comments.id, id)) + .returning(); + } else { + [row] = await tx + .insert(comments) + .values({ + taskId, + authorId: actor.user.id, + body: toDocument(input.body), + }) + .returning(); + } + return { + ...row!, + author: actor.user.name, + createdAt: row!.createdAt.toISOString(), + updatedAt: row!.updatedAt.toISOString(), + }; + }); + } + async activity(actor: Actor, householdId: string, taskId: string, offset: number) { + await this.task(actor, householdId, taskId); + const rows = await this.db + .select({ + id: taskActivities.id, + author: users.name, + fields: taskActivities.fields, + createdAt: taskActivities.createdAt, + }) + .from(taskActivities) + .leftJoin(users, eq(users.id, taskActivities.actorId)) + .where(eq(taskActivities.taskId, taskId)) + .orderBy(desc(taskActivities.createdAt), desc(taskActivities.id)) + .offset(offset) + .limit(51); + return { + items: rows.slice(0, 50).map((r) => ({ + ...r, + author: r.author ?? '—', + createdAt: r.createdAt.toISOString(), + })), + nextOffset: rows.length > 50 ? offset + 50 : null, + }; + } + async files(actor: Actor, householdId: string, taskId: string) { + await this.task(actor, householdId, taskId); + return ( + await this.db + .select() + .from(attachments) + .where( + and( + eq(attachments.householdId, householdId), + eq(attachments.taskId, taskId), + eq(attachments.deleted, false), + ), + ) + .orderBy(desc(attachments.createdAt)) + ).map((f) => ({ ...f, createdAt: f.createdAt.toISOString() })); + } + async search( + actor: Actor, + householdId: string, + q: string, + offset: number, + filterIds: string[] = [], + ) { + return searchContent(this.db, actor, householdId, q, offset, filterIds); + } + async file(actor: Actor, householdId: string, id: string) { + await this.tasks.scope(this.db, actor, householdId); + const [file] = await this.db + .select({ file: attachments }) + .from(attachments) + .innerJoin(tasks, eq(tasks.id, attachments.taskId)) + .where( + and( + eq(attachments.id, id), + eq(attachments.householdId, householdId), + eq(tasks.householdId, householdId), + eq(attachments.deleted, false), + isNull(tasks.trashedAt), + ), + ); + if (!file) throw new AccountError('file_not_found', 404); + return file.file; + } +} diff --git a/apps/api/src/db/schema.ts b/apps/api/src/db/schema.ts index 639e9c8..d4c820e 100644 --- a/apps/api/src/db/schema.ts +++ b/apps/api/src/db/schema.ts @@ -6,3 +6,7 @@ export const installation = pgTable('installation', { }); export * from '../accounts/schema.js'; export * from '../tasks/schema.js'; + +export * from '../content/schema.js'; + +export * from "../views/schema.js"; diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts index 077bc7b..2ad99be 100644 --- a/apps/api/src/main.ts +++ b/apps/api/src/main.ts @@ -18,6 +18,7 @@ const mail = new MailService(db, config.APP_ENCRYPTION_KEY, config.PUBLIC_ORIGIN await boss.send('account-mail', payload, { retryLimit: 3, retryDelay: 30, expireInSeconds: 60 }); }); const app = await buildApp({ + attachmentRoot: config.ATTACHMENT_ROOT, attachmentLimit: config.ATTACHMENT_MAX_BYTES, version: config.APP_VERSION, logLevel: config.LOG_LEVEL, accounts: { service, mail }, closeDatabase: async () => { await boss.stop(); await pool.end(); }, checkDatabase: async () => { await pool.query('SELECT 1'); }, diff --git a/apps/api/src/tasks/schema.ts b/apps/api/src/tasks/schema.ts index 8d78733..d3392a3 100644 --- a/apps/api/src/tasks/schema.ts +++ b/apps/api/src/tasks/schema.ts @@ -15,7 +15,7 @@ export const entities = pgTable('planning_entities', { export const tasks = pgTable('tasks', { id: uuid('id').primaryKey().defaultRandom(), householdId: uuid('household_id').notNull().references(() => households.id, { onDelete: 'cascade' }), - title: text('title').notNull(), description: text('description').notNull().default(''), + title: text('title').notNull(), description: jsonb('description').$type().notNull().default(''), status: statusEnum('status').notNull().default('todo'), bucket: bucketEnum('planning_bucket').notNull().default('someday'), precedingColumn: text('preceding_column'), epicId: uuid('epic_id').references(() => entities.id, { onDelete: 'set null' }), diff --git a/apps/api/src/tasks/service.ts b/apps/api/src/tasks/service.ts index b2a829a..1b1cca7 100644 --- a/apps/api/src/tasks/service.ts +++ b/apps/api/src/tasks/service.ts @@ -1,4 +1,7 @@ -import { and, asc, eq, gt, inArray, isNull, max } from 'drizzle-orm'; +import { ViewService } from '../views/service.js'; +import { validateReferences } from '../content/references.js'; +import { toDocument } from '@tendly/shared'; +import { and, asc, eq, inArray, isNull, max } from 'drizzle-orm'; import { z } from 'zod'; import { taskFields, taskSchema, entitySchema, type Task, type TaskChanges, type TaskFields, type taskCreateSchema, type entityCreateSchema, type entityPatchSchema } from '@tendly/shared'; import type { Database, QueryDatabase, Transaction } from '../accounts/database.js'; @@ -26,7 +29,7 @@ export class TaskService { const [row] = await db.select().from(planningSettings).where(eq(planningSettings.householdId, householdId)); return row ? { version: row.version, thresholds: row.thresholds } : { version: 0, thresholds: [60, 240, 480, 1440] as [number, number, number, number] }; } - async hydrate(db: QueryDatabase, rows: Row[], timezone: string): Promise { + async hydrate(db: QueryDatabase, rows: Row[], timezone: string, now = Date.now()): Promise { if (!rows.length) return []; const ids = rows.map(r => r.id); const links = await db.select({ taskId: taskEntities.taskId, id: entities.id, kind: entities.kind }).from(taskEntities).innerJoin(entities, eq(entities.id, taskEntities.entityId)).where(inArray(taskEntities.taskId, ids)); @@ -34,7 +37,7 @@ export class TaskService { return rows.map(row => { const column = taskColumn(row); return taskSchema.parse({ - ...row, column, ...availability({ ...row, column }, timezone), + ...row, column, ...availability({ ...row, column }, timezone, now), createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString(), completedAt: row.completedAt?.toISOString() ?? null, assignees: assignees.filter(a => a.taskId === row.id).map(a => a.userId).sort(), places: links.filter(l => l.taskId === row.id && l.kind === 'place').map(l => l.id).sort(), @@ -49,25 +52,13 @@ export class TaskService { return (await this.hydrate(db, [row], timezone))[0]!; } async list(actor: Actor, householdId: string, view: 'now' | 'board', offset: number, limit: number) { - const household = await this.scope(this.db, actor, householdId); - const selected: Row[] = []; - let cursor = -1, matched = 0, more = true; - // Bound each scan; filter before pagination. There is no silent household task cap. - // Stage 5's filter compiler will extend this same effective-result boundary. - while (more && selected.length <= limit) { - const batch = await this.db.select().from(tasks).where(and(eq(tasks.householdId, householdId), isNull(tasks.trashedAt), isNull(tasks.archivedAt), gt(tasks.order, cursor))).orderBy(asc(tasks.order)).limit(256); - more = batch.length === 256; - for (const row of batch) { - cursor = row.order; - const column = taskColumn(row); - if (view === 'now' && (!['within_month', 'todo', 'in_progress'].includes(column) || !availability({ ...row, column }, household.timezone).available)) continue; - if (matched++ >= offset) selected.push(row); - if (selected.length > limit) break; - } - } - return { items: await this.hydrate(this.db, selected.slice(0, limit), household.timezone), nextOffset: selected.length > limit ? offset + limit : null }; + const views = new ViewService(this.db); + const catalog = await views.catalog(actor, householdId); + const selected = catalog.views.find(v => v.builtin === view)!; + return views.query(actor, householdId, { viewId: selected.id, offset, limit }); } async validate(db: QueryDatabase, householdId: string, value: TaskFields, previous?: Task) { + await validateReferences(db, householdId, previous?.id, value.description, previous?.description); if ((!value.startDate && value.startTime) || (!value.deadlineDate && value.deadlineTime)) throw new AccountError('date_required'); const expected = [ ...(value.epicId ? [{ id: value.epicId, kind: 'epic' }] : []), @@ -94,7 +85,7 @@ export class TaskService { values(value: TaskFields) { const { column: _column, places: _places, resources: _resources, tags: _tags, assignees: _assignees, ...plain } = value; void _column; void _places; void _resources; void _tags; void _assignees; - return plain; + return { ...plain, description: toDocument(plain.description) }; } async create(actor: Actor, householdId: string, input: z.infer) { return this.db.transaction(async tx => { @@ -115,7 +106,9 @@ export class TaskService { }); } async patch(actor: Actor, householdId: string, id: string, baseVersion: number, changes: TaskChanges, confirmUnavailable = false) { - return this.db.transaction(async tx => { + return this.db.transaction(tx => this.patchInTransaction(tx, actor, householdId, id, baseVersion, changes, confirmUnavailable)); + } + async patchInTransaction(tx: Transaction, actor: Actor, householdId: string, id: string, baseVersion: number, changes: TaskChanges, confirmUnavailable = false) { const household = await this.scope(tx, actor, householdId, true); const [row] = await tx.select().from(tasks).where(and(eq(tasks.id, id), eq(tasks.householdId, householdId), isNull(tasks.trashedAt))).for('update'); if (!row) throw new AccountError('task_not_found', 404); @@ -152,7 +145,6 @@ export class TaskService { await this.collections(tx, id, next); await tx.insert(taskActivities).values({ taskId: id, actorId: actor.user.id, version, fields: [...changed] }); return this.get(tx, householdId, id, household.timezone); - }); } async entityList(actor: Actor, householdId: string) { await this.scope(this.db, actor, householdId); diff --git a/apps/api/src/tasks/tasks.integration.test.ts b/apps/api/src/tasks/tasks.integration.test.ts index 5ef95c1..f00e7a4 100644 --- a/apps/api/src/tasks/tasks.integration.test.ts +++ b/apps/api/src/tasks/tasks.integration.test.ts @@ -1,6 +1,10 @@ +import { readFile, mkdtemp, rm, writeFile, utimes, readdir } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; import { beforeAll, afterAll, expect, it } from 'vitest'; import { randomUUID } from 'node:crypto'; import pg from 'pg'; +import { eq } from 'drizzle-orm'; import { drizzle } from 'drizzle-orm/node-postgres'; import * as schema from '../db/schema.js'; import { migrateDatabase } from '../db/migrate.js'; @@ -9,7 +13,10 @@ import { MailService } from '../accounts/mail.js'; import { digest } from '../accounts/crypto.js'; import { TaskService } from './service.js'; import { buildApp } from '../app.js'; +import { ContentService } from '../content/service.js'; +import { FileStore } from '../content/files.js'; +let fileRoot: string; let planning: TaskService; const origin = 'https://accounts.example.test'; const databaseName = `tendly_test_${randomUUID().replaceAll('-', '')}`; @@ -46,10 +53,12 @@ beforeAll(async () => { await db.insert(schema.households).values([{ id: householdA, name: 'A', timezone: 'Europe/Stockholm' }, { id: householdB, name: 'B', timezone: 'UTC' }]); await db.insert(schema.memberships).values([{ householdId: householdA, userId: userA, role: 'admin' }, { householdId: householdB, userId: userB, role: 'member' }]); sessionA = await service.session(db, userA); sessionB = await service.session(db, userB); - app = await buildApp({ checkDatabase: async () => {}, accounts: { service, mail: new MailService(db, 'ab'.repeat(32), origin, async () => {}) } }); + fileRoot = await mkdtemp(join(tmpdir(),'tendly-files-')); + app = await buildApp({ attachmentRoot:fileRoot, attachmentLimit:100_000, checkDatabase: async () => {}, accounts: { service, mail: new MailService(db, 'ab'.repeat(32), origin, async () => {}) } }); }, 30000); afterAll(async () => { await app?.close(); await pool?.end(); + if(fileRoot) await rm(fileRoot,{recursive:true,force:true}); if (root) { await root.query(`DROP DATABASE IF EXISTS "${databaseName}"`); await root.end(); } }); it('scopes every task/entity request and rejects foreign references and CSRF', async () => { @@ -114,3 +123,92 @@ it('releases a removed member’s assignments without allowing stale editors to await expect(planning.patch(actor, householdA, task.id, task.version, { assignees: [userB] })).rejects.toThrow('task_conflict'); expect((await planning.patch(actor, householdA, task.id, task.version, { title: 'Still editable' })).title).toBe('Still editable'); }); + +it('pushes committed changes only within the household and closes revoked sessions', async () => { + const bearer = await service.session(db, userA); + const socket = await app.injectWS(`/api/v1/households/${householdA}/events`, { headers: headers(bearer), socket: { remoteAddress: '127.0.0.1' } }); + const messages: string[] = [], foreignMessages: string[] = []; + socket.on('message', value => messages.push(String(value))); + const foreign = await app.injectWS(`/api/v1/households/${householdB}/events`, { headers: headers(sessionB), socket: { remoteAddress: '127.0.0.1' } }); + foreign.on('message', value => foreignMessages.push(String(value))); + try { + await expect.poll(() => messages.length).toBe(1); + await expect.poll(() => foreignMessages.length).toBe(1); + const path = `/api/v1/households/${householdA}/tasks`; + const create = await app.inject({ method: 'POST', url: path, headers: headers(sessionA), payload: { title: 'Live update' } }); + expect(create.statusCode).toBe(200); + await expect.poll(() => messages.length).toBe(2); + expect(messages.map(value => JSON.parse(value).type)).toEqual(['invalidate','invalidate']); + expect(foreignMessages).toHaveLength(1); + const rejected = await app.inject({ method: 'POST', url: path, headers: headers(sessionA), payload: { title: '' } }); + expect(rejected.statusCode).toBe(400); + await db.delete(schema.sessions).where(eq(schema.sessions.id, digest(bearer))); + let closeCode: number | undefined; + socket.on('close', code => { closeCode = code; }); + await app.inject({ method: 'POST', url: path, headers: headers(sessionA), payload: { title: 'After revocation' } }); + await expect.poll(() => closeCode).toBe(1008); + expect(messages).toHaveLength(2); + expect(foreignMessages).toHaveLength(1); + } finally { socket.close(); foreign.close(); } +}); + +it('preserves rich content, enforces comment authorship/versioning and scopes search/files', async () => { + const doc=(text:string)=>({type:'doc',content:[{type:'paragraph',content:[{type:'text',text}]}]}); + const task=await planning.create((await service.findSession(sessionA))!,householdA,{title:'Content integration'}); + const path=`/api/v1/households/${householdA}/tasks/${task.id}`; + const rich=await app.inject({method:'PATCH',url:path,headers:headers(sessionA),payload:{baseVersion:task.version,changes:{description:doc('Original rich description')}}}); + expect(rich.statusCode).toBe(200); + const comment=await app.inject({method:'POST',url:path+'/comments',headers:headers(sessionA),payload:{body:doc('SearchableNeedle')}}); + expect(comment.statusCode).toBe(200); + const c=comment.json(); + expect((await app.inject({url:path+'/comments',headers:headers(sessionB)})).statusCode).toBe(404); + const member=randomUUID();await db.insert(schema.users).values({id:member,email:member+'@example.test',name:'Content member'}); + await db.insert(schema.memberships).values({householdId:householdA,userId:member,role:'member'}); + const memberSession=await service.session(db,member); + const settingsUrl=`/api/v1/households/${householdA}`; + const settings={baseName:'A',baseTimezone:'Europe/Stockholm',name:'Content home',timezone:'Europe/Stockholm'}; + expect((await app.inject({method:'PATCH',url:settingsUrl,headers:headers(memberSession),payload:settings})).statusCode).toBe(403); + expect((await app.inject({method:'PATCH',url:settingsUrl,headers:headers(sessionB),payload:settings})).statusCode).toBe(404); + expect((await app.inject({method:'PATCH',url:settingsUrl,headers:headers(sessionA),payload:settings})).statusCode).toBe(200); + expect((await app.inject({method:'PATCH',url:settingsUrl,headers:headers(sessionA),payload:settings})).statusCode).toBe(409); + expect((await app.inject({method:'PATCH',url:path+'/comments/'+c.id,headers:headers(memberSession),payload:{baseVersion:1,body:doc('Not mine')}})).statusCode).toBe(403); + const edit=await app.inject({method:'PATCH',url:path+'/comments/'+c.id,headers:headers(sessionA),payload:{baseVersion:1,body:doc('SearchableNeedle edited')}}); + expect(edit.statusCode).toBe(200); + expect((await app.inject({method:'PATCH',url:path+'/comments/'+c.id,headers:headers(sessionA),payload:{baseVersion:1,deleted:true}})).statusCode).toBe(409); + const search=await app.inject({url:`/api/v1/households/${householdA}/search?q=SearchableNeedle`,headers:headers(sessionA)}); + expect(search.statusCode).toBe(200);expect(search.json().items).toEqual(expect.arrayContaining([expect.objectContaining({kind:'comment',taskId:task.id})])); + expect((await app.inject({url:`/api/v1/households/${householdA}/search?q=SearchableNeedle`,headers:headers(sessionB)})).statusCode).toBe(404); + for(const name of ['photo.png','photo.heic']) { + const bytes=await readFile(new URL('../../../../tests/fixtures/'+name,import.meta.url)); + const boundary='tendly-test-boundary'; + const payload=Buffer.concat([Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="${name}"\r\nContent-Type: application/octet-stream\r\n\r\n`),bytes,Buffer.from(`\r\n--${boundary}--\r\n`)]); + const upload=await app.inject({method:'POST',url:path+'/attachments',headers:{...headers(sessionA),'content-type':`multipart/form-data; boundary=${boundary}`},payload}); + expect(upload.statusCode,upload.body).toBe(200); + const f=upload.json();expect(f.preview).toBe(true); + const url=`/api/v1/households/${householdA}/attachments/${f.id}`; + expect((await app.inject({url:url+'/download',headers:headers(sessionA)})).rawPayload).toEqual(bytes); + const preview=await app.inject({url:url+'/preview',headers:headers(sessionA)}); + expect(preview.statusCode).toBe(200);expect(preview.headers['content-type']).toContain('image/jpeg'); + expect((await app.inject({url:url+'/download',headers:headers(sessionB)})).statusCode).toBe(404); + const foreignDoc={type:'doc',content:[{type:'image',attrs:{src:url.replace(householdA,householdB)+'/preview'}}]}; + expect((await app.inject({method:'POST',url:path+'/comments',headers:headers(sessionA),payload:{body:foreignDoc}})).statusCode).toBe(400); + } + const boundary='oversized';const tooLarge=Buffer.concat([Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="large.txt"\r\n\r\n`),Buffer.alloc(100_001,65),Buffer.from(`\r\n--${boundary}--\r\n`)]); + expect((await app.inject({method:'POST',url:path+'/attachments',headers:{...headers(sessionA),'content-type':`multipart/form-data; boundary=${boundary}`},payload:tooLarge})).statusCode).toBe(413); +}); + +it('removes only old orphaned files and preserves committed originals and previews', async () => { + const store=new FileStore(new ContentService(db),fileRoot); + const existing=await readdir(fileRoot); + expect(existing.length).toBeGreaterThan(0); + const old=new Date(Date.now()-48*3600_000); + for(const file of existing)await utimes(join(fileRoot,file),old,old); + const orphan=store.path(randomUUID()),pending=store.path(randomUUID()); + await writeFile(orphan,'interrupted upload');await utimes(orphan,old,old); + await writeFile(pending,'upload has not committed yet'); + await store.cleanupOrphans(); + const remaining=await readdir(fileRoot); + expect(remaining).toEqual(expect.arrayContaining(existing)); + expect(remaining).toContain(pending.split('/').at(-1)); + await expect(readFile(orphan)).rejects.toMatchObject({code:'ENOENT'}); +}); diff --git a/apps/api/src/views/compiler.ts b/apps/api/src/views/compiler.ts new file mode 100644 index 0000000..693ebca --- /dev/null +++ b/apps/api/src/views/compiler.ts @@ -0,0 +1,75 @@ +import { sql, type SQL } from 'drizzle-orm'; +import { Temporal } from '@js-temporal/polyfill'; +import { parseExpression, type FilterExpression, type FilterValue } from '@tendly/shared'; +export type FilterContext = { + userId: string; + currentPlaceId: string | null; + timezone: string; + now: number; +}; +export function compileFilter( + input: unknown[], + context: FilterContext, +): { predicate: SQL; warnings: string[] } { + const expressions = input.map(parseExpression); + const warnings = new Set(); + const resolve = (value: FilterValue): Exclude | string[] => { + if (!value || typeof value !== 'object' || Array.isArray(value)) return value; + if (value.token === 'CURRENT_USER') return [context.userId]; + if (value.token === 'CURRENT_PLACE') { + if (!context.currentPlaceId) warnings.add('choose_current_place'); + return context.currentPlaceId ? [context.currentPlaceId] : []; + } + return Temporal.Instant.fromEpochMilliseconds(context.now) + .toZonedDateTimeISO(context.timezone) + .toPlainDate() + .add({ days: value.offsetDays ?? 0 }) + .toString(); + }; + const visit = (node: FilterExpression): SQL => { + if (node.type === 'group') { + const children = node.children.map(visit); + if (node.operator === 'NOT') return sql`NOT (${children[0]})`; + if (!children.length) return node.operator === 'AND' ? sql`true` : sql`false`; + return sql`(${sql.join(children, node.operator === 'AND' ? sql` AND ` : sql` OR `)})`; + } + const { field, operator } = node; + const value = resolve(node.value); + const set = ['assignees', 'places', 'resources', 'tags'].includes(field); + const key = field === 'description' ? '_descriptionText' : field; + const raw = sql`item->>${key}`; + const array = sql`COALESCE(item->${key}, '[]'::jsonb)`; + const empty = set + ? sql`jsonb_array_length(${array}) = 0` + : sql`(${raw} IS NULL OR ${raw} = '')`; + if (operator === 'EMPTY') return empty; + if (operator === 'NOT_EMPTY') return sql`NOT (${empty})`; + const operand = + typeof value === 'boolean' + ? sql`(${raw})::boolean` + : typeof value === 'number' + ? sql`(${raw})::numeric` + : ['createdAt', 'completedAt'].includes(field) + ? sql`((${raw})::timestamptz AT TIME ZONE ${context.timezone})::date::text` + : raw; + if (operator === 'EQ') return sql`${operand} IS NOT DISTINCT FROM ${value}`; + if (operator === 'NE') return sql`${operand} IS DISTINCT FROM ${value}`; + if (operator === 'CONTAINS') + return sql`strpos(lower(COALESCE(${raw}, '')), lower(${value})) > 0`; + if (operator === 'LT') return sql`COALESCE(${operand} < ${value}, false)`; + if (operator === 'LTE') return sql`COALESCE(${operand} <= ${value}, false)`; + if (operator === 'GT') return sql`COALESCE(${operand} > ${value}, false)`; + if (operator === 'GTE') return sql`COALESCE(${operand} >= ${value}, false)`; + const values = Array.isArray(value) ? value : []; + if (operator === 'ALL') return sql`${array} @> ${JSON.stringify(values)}::jsonb`; + if (operator === 'FEASIBLE') return sql`${array} <@ ${JSON.stringify(values)}::jsonb`; + const overlap = set + ? sql`EXISTS (SELECT 1 FROM jsonb_array_elements_text(${array}) v WHERE v IN (SELECT jsonb_array_elements_text(${JSON.stringify(values)}::jsonb)))` + : sql`COALESCE(${raw} IN (SELECT jsonb_array_elements_text(${JSON.stringify(values)}::jsonb)), false)`; + if (operator === 'COMPATIBLE') return sql`(${empty} OR ${overlap})`; + return operator === 'NOT_IN' ? sql`NOT (${overlap})` : overlap; + }; + const predicate = sql`(${sql.join(expressions.map(visit), sql` AND `)})`; + // Missing context is not false that NOT can accidentally turn into a broad match. + return { predicate: warnings.size ? sql`false` : predicate, warnings: [...warnings] }; +} diff --git a/apps/api/src/views/defaults.ts b/apps/api/src/views/defaults.ts new file mode 100644 index 0000000..bcc322a --- /dev/null +++ b/apps/api/src/views/defaults.ts @@ -0,0 +1,59 @@ +import { allTasks, nowExpression, type FilterExpression, type ViewFields } from '@tendly/shared'; +export const defaultFilters: Record< + string, + { + name: string; + icon: 'flag' | 'user' | 'map-pin' | 'clock'; + color: 'red' | 'blue' | 'green'; + expression: FilterExpression; + } +> = { + high: { + name: 'High priority', + icon: 'flag', + color: 'red', + expression: { type: 'predicate', field: 'high', operator: 'EQ', value: true }, + }, + mine: { + name: 'Assigned to me', + icon: 'user', + color: 'blue', + expression: { + type: 'predicate', + field: 'assignees', + operator: 'IN', + value: { token: 'CURRENT_USER' }, + }, + }, + here: { + name: 'At my current place', + icon: 'map-pin', + color: 'green', + expression: { + type: 'predicate', + field: 'places', + operator: 'COMPATIBLE', + value: { token: 'CURRENT_PLACE' }, + }, + }, + small: { + name: 'Small tasks', + icon: 'clock', + color: 'blue', + expression: { type: 'predicate', field: 'size', operator: 'IN', value: ['XS', 'S'] }, + }, +}; +export function defaultView(builtin: 'now' | 'board', quickFilters: string[]): ViewFields { + return { + name: builtin === 'now' ? 'Now' : 'Board', + icon: builtin === 'now' ? 'house' : 'layout-grid', + color: 'blue', + presentation: builtin === 'now' ? 'list' : 'board', + expression: builtin === 'now' ? nowExpression : allTasks, + quickFilters, + sort: 'manual', + epicLanes: false, + showEmptyLanes: false, + cardProperties: ['epic', 'size', 'high', 'deadline', 'assignees'], + }; +} diff --git a/apps/api/src/views/move.ts b/apps/api/src/views/move.ts new file mode 100644 index 0000000..f2cd847 --- /dev/null +++ b/apps/api/src/views/move.ts @@ -0,0 +1,108 @@ +import { and, asc, eq, isNull, sql } from 'drizzle-orm'; +import type { z } from 'zod'; +import type { moveTaskSchema, TaskChanges } from '@tendly/shared'; +import type { Actor } from '../accounts/access.js'; +import type { Database } from '../accounts/database.js'; +import { AccountError } from '../accounts/errors.js'; +import { TaskService, TaskConflict } from '../tasks/service.js'; +import { tasks, taskActivities } from '../tasks/schema.js'; +import { taskOrderVersions } from './schema.js'; +export async function moveTask( + db: Database, + actor: Actor, + householdId: string, + id: string, + input: z.infer, +) { + const service = new TaskService(db); + return db.transaction(async (tx) => { + const home = await service.scope(tx, actor, householdId, true); + const all = await tx + .select() + .from(tasks) + .where(and(eq(tasks.householdId, householdId), isNull(tasks.trashedAt))) + .orderBy(asc(tasks.order)); + const index = all.findIndex((t) => t.id === id), + original = all[index]; + if (!original) throw new AccountError('task_not_found', 404); + const [order] = await tx + .select() + .from(taskOrderVersions) + .where(eq(taskOrderVersions.householdId, householdId)); + const reorder = input.beforeId !== undefined || input.afterId !== undefined; + if (reorder && (order?.version ?? 0) !== input.orderVersion) + throw new AccountError('order_conflict', 409); + const current = await service.get(tx, householdId, id, home.timezone); + if ( + reorder && + ((original.fieldVersions.order ?? 1) > input.baseVersion || + input.baseVersion > original.version) + ) + throw new TaskConflict(current, ['order']); + const inverse = { + beforeId: all[index + 1]?.id ?? null, + column: current.column, + epicId: current.epicId, + }; + const changes: TaskChanges = { + ...(input.column === undefined ? {} : { column: input.column }), + ...(input.epicId === undefined ? {} : { epicId: input.epicId }), + }; + if (!reorder && !Object.keys(changes).length) throw new AccountError('invalid_input'); + let rank = original.order; + if (reorder) { + const rest = all.filter((t) => t.id !== id); + const anchor = input.beforeId ?? input.afterId; + if (anchor === id) throw new AccountError('invalid_order_target'); + const at = anchor ? rest.findIndex((t) => t.id === anchor) : rest.length; + if (at < 0) throw new AccountError('invalid_order_target'); + const insert = anchor && input.afterId ? at + 1 : at; + const low = rest[insert - 1]?.order ?? 0, + high = rest[insert]?.order ?? low + 2048; + rank = (low + high) / 2; + if (high - low < 0.00001) { + // Re-spacing changes representation, not relative order or anyone's content. + for (let i = 0; i < rest.length; i++) { + rest[i]!.order = (i + 1) * 1024; + await tx.update(tasks).set({ order: rest[i]!.order }).where(eq(tasks.id, rest[i]!.id)); + } + const lower = rest[insert - 1]?.order ?? 0; + rank = (lower + (rest[insert]?.order ?? lower + 2048)) / 2; + } + } + const next = await service.patchInTransaction( + tx, + actor, + householdId, + id, + input.baseVersion, + changes, + input.confirmUnavailable, + ); + if (reorder) { + await tx + .update(tasks) + .set({ + order: rank, + fieldVersions: sql`${tasks.fieldVersions} || ${JSON.stringify({ order: next.version })}::jsonb`, + }) + .where(eq(tasks.id, id)); + await tx + .update(taskActivities) + .set({ fields: [...Object.keys(changes), 'order'] }) + .where(and(eq(taskActivities.taskId, id), eq(taskActivities.version, next.version))); + await tx + .insert(taskOrderVersions) + .values({ householdId, version: input.orderVersion + 1 }) + .onConflictDoUpdate({ + target: taskOrderVersions.householdId, + set: { version: input.orderVersion + 1 }, + }); + } + return { + task: await service.get(tx, householdId, id, home.timezone), + orderVersion: reorder ? input.orderVersion + 1 : (order?.version ?? 0), + inverse, + }; + }); +} diff --git a/apps/api/src/views/query.ts b/apps/api/src/views/query.ts new file mode 100644 index 0000000..6b063cf --- /dev/null +++ b/apps/api/src/views/query.ts @@ -0,0 +1,96 @@ +import { and, asc, eq, gt, isNull, sql } from 'drizzle-orm'; +import { + filterFields, + plainText, + taskSchema, + type FilterExpression, + type Task, + type ViewFields, +} from '@tendly/shared'; +import type { QueryDatabase } from '../accounts/database.js'; +import { tasks } from '../tasks/schema.js'; +import type { TaskService } from '../tasks/service.js'; +import { compileFilter, type FilterContext } from './compiler.js'; + +export function taskComparator(sort: ViewFields['sort']) { + const nullLast = (a: string | number | null, b: string | number | null) => + a === b ? 0 : a === null ? 1 : b === null ? -1 : a < b ? -1 : 1; + return (a: Task, b: Task) => { + let difference = 0; + if (sort === 'deadline') + difference = nullLast( + a.deadlineDate ? a.deadlineDate + 'T' + (a.deadlineTime ?? '23:59:59') : null, + b.deadlineDate ? b.deadlineDate + 'T' + (b.deadlineTime ?? '23:59:59') : null, + ); + if (sort === 'high') difference = Number(b.high) - Number(a.high); + if (sort === 'effort') { + const rank = (t: Task) => (t.size ? ['XS', 'S', 'M', 'L', 'XL'].indexOf(t.size) : null); + difference = nullLast(rank(a), rank(b)) || nullLast(a.estimateMinutes, b.estimateMinutes); + } + if (sort === 'created') difference = b.createdAt.localeCompare(a.createdAt); + return difference || a.order - b.order || a.id.localeCompare(b.id); + }; +} +// This projection is the integration boundary for Stage 4 inheritance. SQL evaluates +// only canonically hydrated task values, never a competing raw-row interpretation. +export async function matchingTasks( + db: QueryDatabase, + service: TaskService, + householdId: string, + expression: FilterExpression[], + context: FilterContext, + options: { offset: number; limit: number; sort: ViewFields['sort']; includeArchived?: boolean }, +) { + const compiled = compileFilter(expression, context); + if (compiled.warnings.length) + return { items: [] as Task[], count: 0, nextOffset: null, warnings: compiled.warnings }; + let cursor = -1, + count = 0; + const selected: Task[] = []; + const compare = taskComparator(options.sort), + keep = options.offset + options.limit + 1; + while (true) { + const rows = await db + .select() + .from(tasks) + .where( + and( + eq(tasks.householdId, householdId), + isNull(tasks.trashedAt), + options.includeArchived ? undefined : isNull(tasks.archivedAt), + gt(tasks.order, cursor), + ), + ) + .orderBy(asc(tasks.order)) + .limit(256); + if (!rows.length) break; + cursor = rows.at(-1)!.order; + const hydrated = await service.hydrate(db, rows, context.timezone, context.now); + const projection = hydrated.map((task) => ({ + id: task.id, + ...Object.fromEntries( + filterFields + .filter((field) => field !== 'description') + .map((field) => [field, task[field as Exclude]]), + ), + _descriptionText: plainText(task.description), + })); + const matches = await db.execute( + sql`SELECT item->>'id' AS id FROM jsonb_array_elements(${JSON.stringify(projection)}::jsonb) item WHERE ${compiled.predicate}`, + ); + const ids = new Set(matches.rows.map((r) => String(r.id))); + count += ids.size; + selected.push(...hydrated.filter((t) => ids.has(t.id))); + selected.sort(compare); + if (selected.length > keep) selected.length = keep; + if (rows.length < 256) break; + } + return { + items: selected + .slice(options.offset, options.offset + options.limit) + .map((t) => taskSchema.parse(t)), + count, + nextOffset: count > options.offset + options.limit ? options.offset + options.limit : null, + warnings: compiled.warnings, + }; +} diff --git a/apps/api/src/views/routes.ts b/apps/api/src/views/routes.ts new file mode 100644 index 0000000..ea88d2c --- /dev/null +++ b/apps/api/src/views/routes.ts @@ -0,0 +1,208 @@ +import type { FastifyInstance, FastifyRequest } from 'fastify'; +import type { ZodTypeProvider } from 'fastify-type-provider-zod'; +import { z } from 'zod'; +import { + filterFieldsSchema, + savedFilterSchema, + filterVersionSchema, + viewFieldsSchema, + savedViewSchema, + viewStateSchema, + viewContextSchema, + viewCatalogSchema, + taskQuerySchema, + taskQueryResultSchema, + moveTaskSchema, + moveTaskResultSchema, + taskConflictSchema, + errorSchema, +} from '@tendly/shared'; +import type { AccountService } from '../accounts/service.js'; +import { signedIn } from '../accounts/access.js'; +import { TaskConflict } from '../tasks/service.js'; +import { ViewService } from './service.js'; +import { moveTask } from './move.js'; +const scope = z.object({ householdId: z.uuid() }), + item = scope.extend({ id: z.uuid() }); +const revision = z.number().int().positive(); +export async function registerViewRoutes(server: FastifyInstance, accounts: AccountService) { + const app = server.withTypeProvider(), + service = new ViewService(accounts.db); + const cookie = accounts.origin.startsWith('https:') ? '__Host-tendly' : 'tendly_session'; + const actor = async (r: FastifyRequest) => { + const current = await accounts.findSession(r.cookies[cookie]); + signedIn(current); + return current; + }; + app.get( + '/api/v1/households/:householdId/view-catalog', + { schema: { params: scope, response: { 200: viewCatalogSchema } } }, + async (r) => service.catalog(await actor(r), r.params.householdId), + ); + app.post( + '/api/v1/households/:householdId/filters', + { schema: { params: scope, body: filterFieldsSchema, response: { 200: savedFilterSchema } } }, + async (r) => service.filterWrite(await actor(r), r.params.householdId, r.body), + ); + app.put( + '/api/v1/households/:householdId/filters/:id', + { + schema: { + params: item, + body: z.object({ baseVersion: revision, changes: filterFieldsSchema }), + response: { 200: savedFilterSchema }, + }, + }, + async (r) => + service.filterWrite( + await actor(r), + r.params.householdId, + r.body.changes, + r.params.id, + r.body.baseVersion, + ), + ); + app.post( + '/api/v1/households/:householdId/filters/:id/command', + { + schema: { + params: item, + body: z.object({ + baseVersion: revision, + command: z.enum(['delete', 'undelete', 'reset', 'restore']), + version: revision.optional(), + }), + response: { 200: savedFilterSchema }, + }, + }, + async (r) => + service.filterCommand( + await actor(r), + r.params.householdId, + r.params.id, + r.body.baseVersion, + r.body.command, + r.body.version, + ), + ); + app.get( + '/api/v1/households/:householdId/filters/:id/versions', + { schema: { params: item, response: { 200: z.array(filterVersionSchema) } } }, + async (r) => service.history(await actor(r), r.params.householdId, r.params.id), + ); + app.post( + '/api/v1/households/:householdId/views', + { schema: { params: scope, body: viewFieldsSchema, response: { 200: savedViewSchema } } }, + async (r) => service.viewWrite(await actor(r), r.params.householdId, r.body), + ); + app.put( + '/api/v1/households/:householdId/views/:id', + { + schema: { + params: item, + body: z.object({ baseVersion: revision, changes: viewFieldsSchema }), + response: { 200: savedViewSchema }, + }, + }, + async (r) => + service.viewWrite( + await actor(r), + r.params.householdId, + r.body.changes, + r.params.id, + r.body.baseVersion, + ), + ); + app.post( + '/api/v1/households/:householdId/views/:id/command', + { + schema: { + params: item, + body: z.object({ baseVersion: revision, command: z.enum(['delete', 'undelete', 'reset']) }), + response: { 200: savedViewSchema }, + }, + }, + async (r) => + service.viewCommand( + await actor(r), + r.params.householdId, + r.params.id, + r.body.baseVersion, + r.body.command, + ), + ); + app.put( + '/api/v1/households/:householdId/views/:id/state', + { + schema: { + params: item, + body: z.object({ + baseVersion: z.number().int().min(0), + favorite: z.boolean().optional(), + activeFilters: z.array(z.uuid()).max(50).optional(), + }), + response: { 200: viewStateSchema }, + }, + }, + async (r) => + service.stateWrite( + await actor(r), + r.params.householdId, + r.params.id, + r.body.baseVersion, + r.body, + ), + ); + app.put( + '/api/v1/households/:householdId/view-context', + { + schema: { + params: scope, + body: z.object({ + baseVersion: z.number().int().min(0), + currentPlaceId: z.uuid().nullable(), + }), + response: { 200: viewContextSchema }, + }, + }, + async (r) => + service.contextWrite( + await actor(r), + r.params.householdId, + r.body.baseVersion, + r.body.currentPlaceId, + ), + ); + app.post( + '/api/v1/households/:householdId/task-query', + { schema: { params: scope, body: taskQuerySchema, response: { 200: taskQueryResultSchema } } }, + async (r) => service.query(await actor(r), r.params.householdId, r.body), + ); + app.post( + '/api/v1/households/:householdId/tasks/:id/move', + { + schema: { + params: item, + body: moveTaskSchema, + response: { 200: moveTaskResultSchema, 409: z.union([taskConflictSchema, errorSchema]) }, + }, + }, + async (r, reply) => { + try { + return await moveTask( + accounts.db, + await actor(r), + r.params.householdId, + r.params.id, + r.body, + ); + } catch (e) { + if (e instanceof TaskConflict) + return reply + .code(409) + .send({ error: 'task_conflict' as const, current: e.current, fields: e.fields }); + throw e; + } + }, + ); +} diff --git a/apps/api/src/views/schema.ts b/apps/api/src/views/schema.ts new file mode 100644 index 0000000..a71c682 --- /dev/null +++ b/apps/api/src/views/schema.ts @@ -0,0 +1,98 @@ +import { + pgTable, + uuid, + text, + integer, + boolean, + timestamp, + jsonb, + primaryKey, + uniqueIndex, +} from 'drizzle-orm/pg-core'; +import { households, users } from '../accounts/schema.js'; +import { entities } from '../tasks/schema.js'; +import type { FilterExpression, ViewFields } from '@tendly/shared'; +const identity = () => ({ + id: uuid('id').primaryKey().defaultRandom(), + householdId: uuid('household_id') + .notNull() + .references(() => households.id, { onDelete: 'cascade' }), + creatorId: uuid('creator_id').references(() => users.id, { onDelete: 'set null' }), + name: text('name').notNull(), + icon: text('icon').notNull(), + color: text('color').notNull(), + builtin: text('builtin'), + version: integer('version').notNull().default(1), + deleted: boolean('deleted').notNull().default(false), +}); +export const filters = pgTable( + 'saved_filters', + { ...identity(), expression: jsonb('expression').$type().notNull() }, + (t) => [uniqueIndex('filter_builtin_idx').on(t.householdId, t.builtin)], +); +export const filterVersions = pgTable( + 'filter_versions', + { + filterId: uuid('filter_id') + .notNull() + .references(() => filters.id, { onDelete: 'cascade' }), + version: integer('version').notNull(), + authorId: uuid('author_id').references(() => users.id, { onDelete: 'set null' }), + createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(), + snapshot: jsonb('snapshot') + .$type<{ name: string; icon: string; color: string; expression: FilterExpression }>() + .notNull(), + }, + (t) => [primaryKey({ columns: [t.filterId, t.version] })], +); +export const views = pgTable( + 'saved_views', + { + ...identity(), + presentation: text('presentation').notNull(), + expression: jsonb('expression').$type().notNull(), + quickFilters: jsonb('quick_filters').$type().notNull().default([]), + sort: text('sort').notNull().default('manual'), + epicLanes: boolean('epic_lanes').notNull().default(false), + showEmptyLanes: boolean('show_empty_lanes').notNull().default(false), + cardProperties: jsonb('card_properties').$type().notNull(), + }, + (t) => [uniqueIndex('view_builtin_idx').on(t.householdId, t.builtin)], +); +export const viewStates = pgTable( + 'user_view_states', + { + viewId: uuid('view_id') + .notNull() + .references(() => views.id, { onDelete: 'cascade' }), + userId: uuid('user_id') + .notNull() + .references(() => users.id, { onDelete: 'cascade' }), + version: integer('version').notNull().default(1), + favorite: boolean('favorite').notNull().default(false), + activeFilters: jsonb('active_filters').$type().notNull().default([]), + }, + (t) => [primaryKey({ columns: [t.viewId, t.userId] })], +); +export const viewContexts = pgTable( + 'user_view_contexts', + { + householdId: uuid('household_id') + .notNull() + .references(() => households.id, { onDelete: 'cascade' }), + userId: uuid('user_id') + .notNull() + .references(() => users.id, { onDelete: 'cascade' }), + version: integer('version').notNull().default(1), + currentPlaceId: uuid('current_place_id').references(() => entities.id, { + onDelete: 'set null', + }), + }, + (t) => [primaryKey({ columns: [t.householdId, t.userId] })], +); +export const taskOrderVersions = pgTable('task_order_versions', { + householdId: uuid('household_id') + .primaryKey() + .references(() => households.id, { onDelete: 'cascade' }), + version: integer('version').notNull().default(0), +}); diff --git a/apps/api/src/views/service.ts b/apps/api/src/views/service.ts new file mode 100644 index 0000000..3c87cda --- /dev/null +++ b/apps/api/src/views/service.ts @@ -0,0 +1,488 @@ +import { and, asc, desc, eq, inArray } from 'drizzle-orm'; +import { z } from 'zod'; +import { + allTasks, + filterVersionSchema, + filterFieldsSchema, + savedFilterSchema, + savedViewSchema, + viewFieldsSchema, + parseExpression, + type TaskQuery, + type FilterExpression, +} from '@tendly/shared'; +import type { Actor } from '../accounts/access.js'; +import type { Database, QueryDatabase } from '../accounts/database.js'; +import { users, memberships } from '../accounts/schema.js'; +import { entities } from '../tasks/schema.js'; +import { TaskService } from '../tasks/service.js'; +import { AccountError } from '../accounts/errors.js'; +import { + filters, + filterVersions, + views, + viewStates, + viewContexts, + taskOrderVersions, +} from './schema.js'; +import { defaultFilters, defaultView } from './defaults.js'; +import { matchingTasks } from './query.js'; + +type FilterFields = z.infer; +type ViewFields = z.infer; +export class ViewService { + readonly tasks: TaskService; + constructor(readonly db: Database) { + this.tasks = new TaskService(db); + } + async initialize(actor: Actor, householdId: string) { + await this.db.transaction(async (tx) => { + await this.tasks.scope(tx, actor, householdId, true); + for (const [builtin, value] of Object.entries(defaultFilters)) { + const [created] = await tx + .insert(filters) + .values({ ...value, builtin, householdId }) + .onConflictDoNothing() + .returning(); + if (created) + await tx + .insert(filterVersions) + .values({ filterId: created.id, version: 1, snapshot: value }); + } + const shared = await tx.select().from(filters).where(eq(filters.householdId, householdId)); + const quick = Object.keys(defaultFilters).map( + (key) => shared.find((f) => f.builtin === key)!.id, + ); + for (const builtin of ['now', 'board'] as const) + await tx + .insert(views) + .values({ + ...defaultView(builtin, quick), + expression: parseExpression(defaultView(builtin, quick).expression), + builtin, + householdId, + }) + .onConflictDoNothing(); + }); + } + async catalog(actor: Actor, householdId: string) { + await this.initialize(actor, householdId); + const [filterRows, viewRows, stateRows, context] = await Promise.all([ + this.db + .select({ row: filters, creator: users.name }) + .from(filters) + .leftJoin(users, eq(users.id, filters.creatorId)) + .where(eq(filters.householdId, householdId)) + .orderBy(asc(filters.name)), + this.db + .select({ row: views, creator: users.name }) + .from(views) + .leftJoin(users, eq(users.id, views.creatorId)) + .where(eq(views.householdId, householdId)) + .orderBy(asc(views.name)), + this.db + .select({ state: viewStates }) + .from(viewStates) + .innerJoin(views, eq(views.id, viewStates.viewId)) + .where(and(eq(views.householdId, householdId), eq(viewStates.userId, actor.user.id))), + this.context(actor, householdId), + ]); + return { + filters: filterRows.map(({ row, creator }) => + savedFilterSchema.parse({ ...row, creator: creator ?? 'Tendly' }), + ), + views: viewRows.map(({ row, creator }) => + savedViewSchema.parse({ ...row, creator: creator ?? 'Tendly' }), + ), + states: Object.fromEntries(stateRows.map(({ state }) => [state.viewId, state])), + context, + }; + } + async context(actor: Actor, householdId: string, db: QueryDatabase = this.db) { + await this.tasks.scope(db, actor, householdId); + const [row] = await db + .select() + .from(viewContexts) + .where( + and(eq(viewContexts.householdId, householdId), eq(viewContexts.userId, actor.user.id)), + ); + return row ?? { version: 0, currentPlaceId: null }; + } + async references(db: QueryDatabase, householdId: string, expression: unknown) { + const tree = parseExpression(expression); + const walk = async (node: FilterExpression): Promise => { + if (node.type === 'group') { + for (const child of node.children) await walk(child); + return; + } + if (!Array.isArray(node.value) || !node.value.length) return; + if (node.field === 'assignees') { + const rows = await db + .select({ id: memberships.userId }) + .from(memberships) + .where( + and(eq(memberships.householdId, householdId), inArray(memberships.userId, node.value)), + ); + if (new Set(node.value).size !== rows.length) + throw new AccountError('invalid_filter_reference'); + } + const kind = ( + { epicId: 'epic', places: 'place', resources: 'resource', tags: 'tag' } as const + )[node.field as 'epicId' | 'places' | 'resources' | 'tags']; + if (kind) { + const rows = await db + .select({ id: entities.id }) + .from(entities) + .where( + and( + eq(entities.householdId, householdId), + eq(entities.kind, kind), + inArray(entities.id, node.value), + ), + ); + if (new Set(node.value).size !== rows.length) + throw new AccountError('invalid_filter_reference'); + } + }; + await walk(tree); + return tree; + } + async filterWrite( + actor: Actor, + householdId: string, + input: FilterFields, + id?: string, + baseVersion?: number, + deleted?: boolean, + ) { + return this.db.transaction(async (tx) => { + await this.tasks.scope(tx, actor, householdId, true); + const expression = deleted + ? parseExpression(input.expression) + : await this.references(tx, householdId, input.expression); + const values = { ...filterFieldsSchema.parse(input), expression }; + let row; + if (id) { + const [old] = await tx + .select() + .from(filters) + .where(and(eq(filters.id, id), eq(filters.householdId, householdId))); + if (!old) throw new AccountError('filter_not_found', 404); + if (old.version !== baseVersion) throw new AccountError('filter_conflict', 409); + [row] = await tx + .update(filters) + .set({ + ...values, + version: old.version + 1, + ...(deleted === undefined ? {} : { deleted }), + }) + .where(eq(filters.id, id)) + .returning(); + } else + [row] = await tx + .insert(filters) + .values({ ...values, householdId, creatorId: actor.user.id }) + .returning(); + await tx.insert(filterVersions).values({ + filterId: row!.id, + version: row!.version, + authorId: actor.user.id, + snapshot: values, + }); + const [creator] = row!.creatorId + ? await tx.select({ name: users.name }).from(users).where(eq(users.id, row!.creatorId)) + : []; + return savedFilterSchema.parse({ ...row, creator: creator?.name ?? 'Tendly' }); + }); + } + async filterCommand( + actor: Actor, + householdId: string, + id: string, + baseVersion: number, + command: 'delete' | 'undelete' | 'reset' | 'restore', + version?: number, + ) { + await this.tasks.scope(this.db, actor, householdId); + const [old] = await this.db + .select() + .from(filters) + .where(and(eq(filters.id, id), eq(filters.householdId, householdId))); + if (!old) throw new AccountError('filter_not_found', 404); + let input: FilterFields = filterFieldsSchema.parse(old); + if (command === 'reset') { + if (!old.builtin || !defaultFilters[old.builtin]) throw new AccountError('no_defaults'); + input = defaultFilters[old.builtin]!; + } + if (command === 'restore') { + const [history] = await this.db + .select() + .from(filterVersions) + .where(and(eq(filterVersions.filterId, id), eq(filterVersions.version, version ?? -1))); + if (!history) throw new AccountError('version_not_found', 404); + input = filterFieldsSchema.parse(history.snapshot); + } + return this.filterWrite( + actor, + householdId, + input, + id, + baseVersion, + command === 'delete' + ? true + : command === 'undelete' || command === 'reset' + ? false + : undefined, + ); + } + async history(actor: Actor, householdId: string, id: string) { + await this.tasks.scope(this.db, actor, householdId); + const rows = await this.db + .select({ + version: filterVersions.version, + createdAt: filterVersions.createdAt, + snapshot: filterVersions.snapshot, + author: users.name, + }) + .from(filterVersions) + .innerJoin(filters, eq(filters.id, filterVersions.filterId)) + .leftJoin(users, eq(users.id, filterVersions.authorId)) + .where(and(eq(filters.householdId, householdId), eq(filters.id, id))) + .orderBy(desc(filterVersions.version)); + if (!rows.length) throw new AccountError('filter_not_found', 404); + return rows.map((r) => + filterVersionSchema.parse({ + ...r, + createdAt: r.createdAt.toISOString(), + author: r.author ?? 'Tendly', + }), + ); + } + async viewWrite( + actor: Actor, + householdId: string, + input: ViewFields, + id?: string, + baseVersion?: number, + deleted?: boolean, + ) { + return this.db.transaction(async (tx) => { + await this.tasks.scope(tx, actor, householdId, true); + const values = { + ...viewFieldsSchema.parse(input), + expression: deleted + ? parseExpression(input.expression) + : await this.references(tx, householdId, input.expression), + }; + const quick = values.quickFilters.length + ? await tx + .select() + .from(filters) + .where( + and( + eq(filters.householdId, householdId), + inArray(filters.id, values.quickFilters), + eq(filters.deleted, false), + ), + ) + : []; + if (new Set(values.quickFilters).size !== quick.length) + throw new AccountError('invalid_filter_reference'); + let row; + if (id) { + const [old] = await tx + .select() + .from(views) + .where(and(eq(views.householdId, householdId), eq(views.id, id))); + if (!old) throw new AccountError('view_not_found', 404); + if (old.version !== baseVersion) throw new AccountError('view_conflict', 409); + if (deleted && old.builtin) throw new AccountError('builtin_view_required', 409); + [row] = await tx + .update(views) + .set({ + ...values, + version: old.version + 1, + ...(deleted === undefined ? {} : { deleted }), + }) + .where(eq(views.id, id)) + .returning(); + } else + [row] = await tx + .insert(views) + .values({ ...values, householdId, creatorId: actor.user.id }) + .returning(); + const [creator] = row!.creatorId + ? await tx.select({ name: users.name }).from(users).where(eq(users.id, row!.creatorId)) + : []; + return savedViewSchema.parse({ ...row, creator: creator?.name ?? 'Tendly' }); + }); + } + async viewCommand( + actor: Actor, + householdId: string, + id: string, + baseVersion: number, + command: 'delete' | 'undelete' | 'reset', + ) { + await this.tasks.scope(this.db, actor, householdId); + const [old] = await this.db + .select() + .from(views) + .where(and(eq(views.id, id), eq(views.householdId, householdId))); + if (!old) throw new AccountError('view_not_found', 404); + const available = await this.db + .select() + .from(filters) + .where(and(eq(filters.householdId, householdId), eq(filters.deleted, false))); + const quick = old.quickFilters.filter((id) => available.some((f) => f.id === id)); + if (command === 'reset' && old.builtin !== 'now' && old.builtin !== 'board') + throw new AccountError('no_defaults'); + const input = + command === 'reset' + ? defaultView( + old.builtin as 'now' | 'board', + Object.keys(defaultFilters).flatMap((key) => + available.filter((f) => f.builtin === key).map((f) => f.id), + ), + ) + : viewFieldsSchema.parse({ ...old, quickFilters: quick }); + return this.viewWrite(actor, householdId, input, id, baseVersion, command === 'delete'); + } + async stateWrite( + actor: Actor, + householdId: string, + id: string, + baseVersion: number, + changes: { favorite?: boolean | undefined; activeFilters?: string[] | undefined }, + ) { + return this.db.transaction(async (tx) => { + await this.tasks.scope(tx, actor, householdId, true); + const [view] = await tx + .select() + .from(views) + .where(and(eq(views.id, id), eq(views.householdId, householdId), eq(views.deleted, false))); + if (!view) throw new AccountError('view_not_found', 404); + const [old] = await tx + .select() + .from(viewStates) + .where(and(eq(viewStates.viewId, id), eq(viewStates.userId, actor.user.id))); + if ((old?.version ?? 0) !== baseVersion) + throw new AccountError('personal_state_conflict', 409); + if (changes.activeFilters?.some((id) => !view.quickFilters.includes(id))) + throw new AccountError('invalid_filter_reference'); + const value = { + ...changes, + activeFilters: changes.activeFilters + ? [...new Set(changes.activeFilters)] + : (old?.activeFilters ?? []), + version: baseVersion + 1, + }; + const [row] = await tx + .insert(viewStates) + .values({ viewId: id, userId: actor.user.id, ...value }) + .onConflictDoUpdate({ target: [viewStates.viewId, viewStates.userId], set: value }) + .returning(); + return row!; + }); + } + async contextWrite( + actor: Actor, + householdId: string, + baseVersion: number, + currentPlaceId: string | null, + ) { + return this.db.transaction(async (tx) => { + await this.tasks.scope(tx, actor, householdId, true); + const old = await this.context(actor, householdId, tx); + if (old.version !== baseVersion) throw new AccountError('personal_state_conflict', 409); + if (currentPlaceId) + await this.references(tx, householdId, { + type: 'predicate', + field: 'places', + operator: 'IN', + value: [currentPlaceId], + }); + const [row] = await tx + .insert(viewContexts) + .values({ householdId, userId: actor.user.id, version: baseVersion + 1, currentPlaceId }) + .onConflictDoUpdate({ + target: [viewContexts.householdId, viewContexts.userId], + set: { version: baseVersion + 1, currentPlaceId }, + }) + .returning(); + return row!; + }); + } + async query(actor: Actor, householdId: string, input: TaskQuery, includeArchived = false) { + return this.db.transaction( + (tx) => this.queryWithin(tx, actor, householdId, input, includeArchived), + { isolationLevel: 'repeatable read', accessMode: 'read only' }, + ); + } + async queryWithin( + db: QueryDatabase, + actor: Actor, + householdId: string, + input: TaskQuery, + includeArchived = false, + ) { + const household = await this.tasks.scope(db, actor, householdId); + let expression: FilterExpression = allTasks, + sort: ViewFields['sort'] = 'manual', + active = input.filterIds ?? []; + if (input.viewId) { + const [view] = await db + .select() + .from(views) + .where( + and( + eq(views.id, input.viewId), + eq(views.householdId, householdId), + eq(views.deleted, false), + ), + ); + if (!view) throw new AccountError('view_not_found', 404); + expression = parseExpression(view.expression); + sort = viewFieldsSchema.shape.sort.parse(view.sort); + const [state] = await db + .select() + .from(viewStates) + .where(and(eq(viewStates.viewId, view.id), eq(viewStates.userId, actor.user.id))); + active = (state?.activeFilters ?? []).filter( + (id) => view.quickFilters.includes(id) && id !== input.replaceFilterId, + ); + } + const definitions = active.length + ? await db + .select() + .from(filters) + .where(and(eq(filters.householdId, householdId), inArray(filters.id, active))) + : []; + if (!input.viewId && new Set(active).size !== definitions.length) + throw new AccountError('invalid_filter_reference'); + const expressions = [ + expression, + ...definitions.filter((f) => !f.deleted).map((f) => f.expression), + ...(input.expression ? [parseExpression(input.expression)] : []), + ]; + const context = await this.context(actor, householdId, db); + const [order] = await db + .select() + .from(taskOrderVersions) + .where(eq(taskOrderVersions.householdId, householdId)); + const result = await matchingTasks( + db, + this.tasks, + householdId, + expressions, + { + userId: actor.user.id, + currentPlaceId: context.currentPlaceId, + timezone: household.timezone, + now: Date.now(), + }, + { offset: input.offset, limit: input.limit, sort, includeArchived }, + ); + return { ...result, orderVersion: order?.version ?? 0 }; + } +} diff --git a/apps/api/src/views/views.integration.test.ts b/apps/api/src/views/views.integration.test.ts new file mode 100644 index 0000000..0aab86e --- /dev/null +++ b/apps/api/src/views/views.integration.test.ts @@ -0,0 +1,484 @@ +import { randomUUID } from 'node:crypto'; +import { beforeAll, afterAll, expect, it } from 'vitest'; +import pg from 'pg'; +import { drizzle } from 'drizzle-orm/node-postgres'; +import { eq } from 'drizzle-orm'; +import { + allTasks, + parseExpression, + viewFieldsSchema, + type FilterExpression, + type TaskQuery, +} from '@tendly/shared'; +import * as schema from '../db/schema.js'; +import { migrateDatabase } from '../db/migrate.js'; +import { AccountService } from '../accounts/service.js'; +import { MailService } from '../accounts/mail.js'; +import { TaskService } from '../tasks/service.js'; +import { ContentService } from '../content/service.js'; +import { buildApp } from '../app.js'; +import { ViewService } from './service.js'; +import { matchingTasks } from './query.js'; +import { moveTask } from './move.js'; +const databaseName = `tendly_views_${randomUUID().replaceAll('-', '')}`, + origin = 'https://views.example.test'; +let root: pg.Client, + pool: pg.Pool, + db: ReturnType>, + accounts: AccountService, + service: ViewService, + tasks: TaskService, + app: Awaited>; +const user = randomUUID(), + other = randomUUID(), + outsider = randomUUID(), + home = randomUUID(), + foreign = randomUUID(); +let actor: NonNullable>>, + member: typeof actor, + intruder: typeof actor, + session: string; +const rule = (field: string, operator: string, value: unknown) => + parseExpression({ type: 'predicate', field, operator, value }); +const and = (...children: FilterExpression[]): FilterExpression => ({ + type: 'group', + operator: 'AND', + children, +}); +const query = (expression: FilterExpression, extra: Partial = {}) => + service.query(actor, home, { expression, offset: 0, limit: 100, ...extra }); +const definition = (name: string, expression: FilterExpression) => ({ + name, + expression, + icon: 'star' as const, + color: 'blue' as const, +}); +beforeAll(async () => { + if (!process.env.TEST_DATABASE_URL) throw new Error('TEST_DATABASE_URL required'); + root = new pg.Client({ connectionString: process.env.TEST_DATABASE_URL }); + await root.connect(); + await root.query(`CREATE DATABASE "${databaseName}"`); + const url = new URL(process.env.TEST_DATABASE_URL); + url.pathname = '/' + databaseName; + await migrateDatabase(url.toString()); + pool = new pg.Pool({ connectionString: url.toString() }); + db = drizzle(pool, { schema }); + accounts = new AccountService(db, origin); + service = new ViewService(db); + tasks = new TaskService(db); + await db.insert(schema.users).values([ + { id: user, name: 'Owner', email: 'owner@views.test' }, + { id: other, name: 'Member', email: 'member@views.test' }, + { id: outsider, name: 'Outsider', email: 'outsider@views.test' }, + ]); + await db.insert(schema.households).values([ + { id: home, name: 'Home', timezone: 'Europe/Stockholm' }, + { id: foreign, name: 'Other', timezone: 'UTC' }, + ]); + await db.insert(schema.memberships).values([ + { householdId: home, userId: user, role: 'admin' }, + { householdId: home, userId: other, role: 'member' }, + { householdId: foreign, userId: outsider, role: 'admin' }, + ]); + session = await accounts.session(db, user); + actor = (await accounts.findSession(session))!; + member = (await accounts.findSession(await accounts.session(db, other)))!; + intruder = (await accounts.findSession(await accounts.session(db, outsider)))!; + app = await buildApp({ + checkDatabase: async () => {}, + accounts: { + service: accounts, + mail: new MailService(db, 'ab'.repeat(32), origin, async () => {}), + }, + }); +}, 30000); +afterAll(async () => { + await app?.close(); + await pool?.end(); + if (root) { + await root.query(`DROP DATABASE IF EXISTS "${databaseName}"`); + await root.end(); + } +}); +it('uses typed set semantics, nested NOT and context values, with missing context never broadening a match', async () => { + const place = await tasks.entityWrite(actor, home, { kind: 'place', name: 'Home' }), + away = await tasks.entityWrite(actor, home, { kind: 'place', name: 'Away' }); + const car = await tasks.entityWrite(actor, home, { kind: 'resource', name: 'Car' }), + trailer = await tasks.entityWrite(actor, home, { kind: 'resource', name: 'Trailer' }); + const a = await tasks.create(actor, home, { + title: 'sets anywhere', + column: 'todo', + assignees: [user], + }), + b = await tasks.create(actor, home, { + title: 'sets both places', + places: [place.id, away.id], + resources: [car.id], + }), + c = await tasks.create(actor, home, { + title: 'sets away', + places: [away.id], + resources: [car.id, trailer.id], + assignees: [other], + }); + const base = rule('title', 'CONTAINS', 'sets '); + expect( + (await query(and(base, rule('places', 'COMPATIBLE', [place.id])))).items.map((t) => t.id), + ).toEqual([a.id, b.id]); + expect( + (await query(and(base, rule('resources', 'FEASIBLE', [car.id])))).items.map((t) => t.id), + ).toEqual([a.id, b.id]); + expect( + (await query(and(base, rule('resources', 'IN', [car.id])))).items.map((t) => t.id), + ).toEqual([b.id, c.id]); + expect( + (await query(and(base, rule('assignees', 'IN', { token: 'CURRENT_USER' })))).items.map( + (t) => t.id, + ), + ).toEqual([a.id]); + expect( + ( + await service.query(member, home, { + expression: and(base, rule('assignees', 'IN', { token: 'CURRENT_USER' })), + offset: 0, + limit: 10, + }) + ).items.map((t) => t.id), + ).toEqual([c.id]); + const missing = await query( + and(base, { + type: 'group', + operator: 'NOT', + children: [rule('places', 'COMPATIBLE', { token: 'CURRENT_PLACE' })], + }), + ); + expect(missing).toMatchObject({ count: 0, warnings: ['choose_current_place'] }); + await service.contextWrite(actor, home, 0, place.id); + expect( + (await query(and(base, rule('places', 'COMPATIBLE', { token: 'CURRENT_PLACE' })))).items.map( + (t) => t.id, + ), + ).toEqual([a.id, b.id]); + expect( + ( + await query( + and(base, { + type: 'group', + operator: 'NOT', + children: [rule('resources', 'FEASIBLE', [car.id])], + }), + ) + ).items.map((t) => t.id), + ).toEqual([c.id]); + const due = await tasks.create(actor, home, { + title: 'timezone task', + deadlineDate: '2026-11-02', + }); + const result = await matchingTasks( + db, + tasks, + home, + [rule('deadlineDate', 'EQ', { token: 'TODAY' })], + { + userId: user, + currentPlaceId: null, + timezone: 'Europe/Stockholm', + now: Date.parse('2026-11-01T23:30:00Z'), + }, + { offset: 0, limit: 10, sort: 'manual' }, + ); + expect(result.items.map((t) => t.id)).toContain(due.id); +}); +it('filters and sorts the whole set before paging or counting and treats SQL-like text as data', async () => { + await db.insert(schema.tasks).values( + Array.from({ length: 280 }, (_, i) => ({ + householdId: home, + title: 'page ' + i, + column: 'todo' as const, + high: i >= 260, + order: 100000 + i * 1024, + createdBy: user, + deadlineDate: i >= 260 ? '2026-12-' + String(30 - (i - 260)).padStart(2, '0') : null, + })), + ); + const filter = and(rule('title', 'CONTAINS', 'page '), rule('high', 'EQ', true)); + const view = await service.viewWrite( + actor, + home, + viewFieldsSchema.parse({ + ...definition('Deadline', filter), + presentation: 'list', + quickFilters: [], + sort: 'deadline', + epicLanes: false, + showEmptyLanes: false, + cardProperties: [], + }), + ); + const one = await service.query(actor, home, { viewId: view.id, offset: 0, limit: 7 }), + two = await service.query(actor, home, { viewId: view.id, offset: 7, limit: 7 }); + expect(one.count).toBe(20); + expect(one.nextOffset).toBe(7); + expect(one.items[0]?.title).toBe('page 279'); + expect(two.items[0]?.title).toBe('page 272'); + expect((await query(rule('title', 'CONTAINS', "' OR true --"))).count).toBe(0); + await expect( + query({ type: 'predicate', field: 'title', operator: 'GT', value: 'x' } as FilterExpression), + ).rejects.toThrow(); +}); +it('combines the shared base and chips with AND while keeping toggles and favorites personal and per view', async () => { + const catalog = await service.catalog(actor, home), + board = catalog.views.find((v) => v.builtin === 'board')!, + now = catalog.views.find((v) => v.builtin === 'now')!, + high = catalog.filters.find((f) => f.builtin === 'high')!; + await service.stateWrite(actor, home, board.id, 0, { activeFilters: [high.id], favorite: true }); + const enabled = await service.query(actor, home, { viewId: board.id, offset: 0, limit: 100 }); + expect(enabled.items.every((t) => t.high)).toBe(true); + const personal = await service.catalog(member, home); + expect(personal.states[board.id]).toBeUndefined(); + expect((await service.catalog(actor, home)).states[now.id]).toBeUndefined(); + await expect(service.stateWrite(actor, home, board.id, 0, { activeFilters: [] })).rejects.toThrow( + 'personal_state_conflict', + ); + const revised = await service.viewWrite( + actor, + home, + { ...board, expression: rule('title', 'CONTAINS', 'sets ') }, + board.id, + board.version, + ); + expect((await service.query(actor, home, { viewId: board.id, offset: 0, limit: 10 })).count).toBe( + 0, + ); + await expect(service.viewWrite(member, home, board, board.id, board.version)).rejects.toThrow( + 'view_conflict', + ); + await expect( + service.viewCommand(actor, home, board.id, revised.version, 'delete'), + ).rejects.toThrow('builtin_view_required'); + const reset = await service.viewCommand(actor, home, board.id, revised.version, 'reset'); + expect(reset.expression).toEqual(allTasks); +}); +it('keeps reusable filter history, refuses races and restores a snapshot as a new revision', async () => { + const created = await service.filterWrite( + actor, + home, + definition('Shared', rule('high', 'EQ', true)), + ); + const edits = await Promise.allSettled( + [actor, member].map((a) => + service.filterWrite( + a, + home, + { ...created, name: 'Edited ' + a.user.id }, + created.id, + created.version, + ), + ), + ); + expect(edits.filter((e) => e.status === 'fulfilled')).toHaveLength(1); + const history = await service.history(actor, home, created.id); + expect(history.map((v) => v.version)).toEqual([2, 1]); + const restored = await service.filterCommand(actor, home, created.id, 2, 'restore', 1); + expect(restored).toMatchObject({ name: 'Shared', version: 3, creatorId: user }); + const deleted = await service.filterCommand(actor, home, created.id, 3, 'delete'); + expect(deleted.deleted).toBe(true); + const revived = await service.filterCommand(actor, home, created.id, 4, 'undelete'); + expect(revived.deleted).toBe(false); + await expect(service.filterCommand(actor, home, created.id, 4, 'restore', 1)).rejects.toThrow( + 'filter_conflict', + ); +}); +it('scopes every new route and rejects cross-household references and move anchors', async () => { + const catalog = await service.catalog(actor, home), + view = catalog.views[0]!, + filter = catalog.filters[0]!, + task = await tasks.create(actor, home, { title: 'private' }); + const foreignEntity = await tasks.entityWrite(intruder, foreign, { + kind: 'place', + name: 'Secret', + }), + foreignTask = await tasks.create(intruder, foreign, { title: 'Secret task' }); + await expect( + service.filterWrite(actor, home, definition('Leak', rule('places', 'IN', [foreignEntity.id]))), + ).rejects.toThrow('invalid_filter_reference'); + await expect(service.contextWrite(actor, home, 1, foreignEntity.id)).rejects.toThrow( + 'invalid_filter_reference', + ); + await expect(query(allTasks, { filterIds: [randomUUID()] })).rejects.toThrow( + 'invalid_filter_reference', + ); + await expect( + moveTask(db, actor, home, task.id, { + baseVersion: 1, + orderVersion: 0, + beforeId: foreignTask.id, + }), + ).rejects.toThrow('invalid_order_target'); + const foreignSession = await accounts.session(db, outsider), + base = '/api/v1/households/' + home; + const requests = [ + ['GET', '/view-catalog', undefined], + ['GET', `/filters/${filter.id}/versions`, undefined], + ['POST', '/filters', definition('x', allTasks)], + ['PUT', `/filters/${filter.id}`, { baseVersion: 1, changes: definition('x', allTasks) }], + ['POST', `/filters/${filter.id}/command`, { baseVersion: 1, command: 'delete' }], + ['POST', '/views', view], + ['PUT', `/views/${view.id}`, { baseVersion: 1, changes: view }], + ['POST', `/views/${view.id}/command`, { baseVersion: 1, command: 'delete' }], + ['PUT', `/views/${view.id}/state`, { baseVersion: 0, favorite: true }], + ['PUT', '/view-context', { baseVersion: 0, currentPlaceId: null }], + ['POST', '/task-query', { viewId: view.id }], + ['POST', `/tasks/${task.id}/move`, { baseVersion: 1, orderVersion: 0, beforeId: null }], + ['POST', '/search', { q: 'private', filterIds: [filter.id] }], + ] as const; + for (const [method, path, payload] of requests) { + for (const token of [undefined, foreignSession]) { + const response = await app.inject({ + method, + url: base + path, + headers: { origin, ...(token ? { cookie: `__Host-tendly=${token}` } : {}) }, + ...(payload ? { payload } : {}), + }); + expect(response.statusCode, method + ' ' + path).toBe(token ? 404 : 401); + } + } +}); +it('moves atomically, preserves one order across views and refuses stale ordering Undo without changing fields', async () => { + const a = await tasks.create(actor, home, { title: 'move a', column: 'todo' }), + b = await tasks.create(actor, home, { title: 'move b', column: 'todo' }), + c = await tasks.create(actor, home, { title: 'move c', column: 'todo' }); + const first = await moveTask(db, actor, home, c.id, { + baseVersion: c.version, + orderVersion: 0, + beforeId: a.id, + column: 'within_month', + }); + expect((await query(rule('title', 'CONTAINS', 'move '))).items.map((t) => t.id)).toEqual([ + c.id, + a.id, + b.id, + ]); + await moveTask(db, member, home, b.id, { + baseVersion: b.version, + orderVersion: first.orderVersion, + beforeId: c.id, + }); + await expect( + moveTask(db, actor, home, c.id, { + baseVersion: first.task.version, + orderVersion: first.orderVersion, + ...first.inverse, + }), + ).rejects.toThrow('order_conflict'); + expect((await tasks.get(db, home, c.id, 'Europe/Stockholm')).column).toBe('within_month'); + const changed = await tasks.patch(member, home, a.id, a.version, { title: 'move a updated' }); + const moved = await moveTask(db, actor, home, a.id, { + baseVersion: a.version, + orderVersion: 2, + afterId: b.id, + }); + expect(moved.task.title).toBe(changed.title); + const undone = await moveTask(db, actor, home, a.id, { + baseVersion: moved.task.version, + orderVersion: moved.orderVersion, + ...moved.inverse, + }); + expect(undone.orderVersion).toBe(4); + await expect( + moveTask(db, actor, home, a.id, { baseVersion: 1, orderVersion: 4, beforeId: null }), + ).rejects.toThrow('task_conflict'); +}); +it('uses the same saved filters for search tasks and their comments before pagination', async () => { + const filter = await service.filterWrite( + actor, + home, + definition('Search high', rule('high', 'EQ', true)), + ); + const content = new ContentService(db), + task = await tasks.create(actor, home, { title: 'searchterm eligible', high: true }); + await tasks.create(actor, home, { title: 'searchterm hidden' }); + await db.insert(schema.comments).values({ + taskId: task.id, + authorId: user, + body: { + type: 'doc', + content: [{ type: 'paragraph', content: [{ type: 'text', text: 'searchterm comment' }] }], + }, + }); + const found = await content.search(actor, home, 'searchterm', 0, [filter.id]); + expect(found.items).toHaveLength(2); + expect(found.items.every((hit) => hit.taskId === task.id)).toBe(true); + await db.update(schema.tasks).set({ trashedAt: new Date() }).where(eq(schema.tasks.id, task.id)); + expect((await content.search(actor, home, 'searchterm', 0, [filter.id])).items).toHaveLength(0); +}); + +it('broadcasts definition edits but never read-only previews or search queries', async () => { + const headers = { origin, cookie: `__Host-tendly=${session}` }; + const socket = await app.injectWS(`/api/v1/households/${home}/events`, { + headers, + socket: { remoteAddress: '127.0.0.1' }, + }); + const messages: string[] = []; + socket.on('message', (value) => messages.push(String(value))); + try { + await expect.poll(() => messages.length).toBe(1); + const base = '/api/v1/households/' + home; + for (const [path, payload] of [ + ['/task-query', { expression: allTasks }], + ['/search', { q: 'sets' }], + ] as const) + expect( + (await app.inject({ method: 'POST', url: base + path, headers, payload })).statusCode, + ).toBe(200); + expect( + ( + await app.inject({ + method: 'POST', + url: base + '/filters', + headers, + payload: definition('Live', allTasks), + }) + ).statusCode, + ).toBe(200); + await expect.poll(() => messages.length).toBe(2); + expect(JSON.parse(messages[1]!).resources).toEqual(['filters']); + } finally { + socket.close(); + } +}); +it('searches formatted words and mentions with the same text projection as description filters', async () => { + const body = { + type: 'doc', + content: [ + { + type: 'heading', + attrs: { level: 2 }, + content: [ + { type: 'text', text: 'hol' }, + { type: 'text', text: 'iday', marks: [{ type: 'bold' }] }, + { type: 'hardBreak' }, + { type: 'text', text: 'plans ' }, + { type: 'mention', attrs: { id: user, label: 'Owner' } }, + ], + }, + ], + }; + const task = await tasks.create(actor, home, { title: 'zz Formatted content', description: body }); + const content = new ContentService(db); + const comment = await content.writeComment(actor, home, task.id, { body }); + const filter = await service.filterWrite( + actor, + home, + definition('Formatted description', rule('description', 'CONTAINS', 'holiday')), + ); + for (const text of ['holiday', '@Owner', 'holiday\nplans']) { + const found = await content.search(actor, home, text, 0, [filter.id]); + expect(found.items.map((hit) => hit.id).sort()).toEqual([task.id, comment.id].sort()); + // Earlier tests populated more than one batch of unrelated tasks. + const global = await content.search(actor, home, text, 0, []); + expect(global.items.map((hit) => hit.id).sort()).toEqual([task.id, comment.id].sort()); + } + expect((await content.search(actor, home, 'holidayplans', 0, [filter.id])).items).toHaveLength(0); + expect((await content.search(actor, home, 'holiday', 1, [filter.id])).items).toHaveLength(1); +}); diff --git a/apps/web/package.json b/apps/web/package.json index 9dd30de..5767034 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -14,6 +14,13 @@ "@simplewebauthn/browser": "14.0.0", "@tanstack/react-query": "5.104.2", "@tendly/shared": "workspace:*", + "@tiptap/extension-image": "3.32.2", + "@tiptap/extension-mention": "3.32.2", + "@tiptap/extension-task-item": "3.32.2", + "@tiptap/extension-task-list": "3.32.2", + "@tiptap/pm": "3.32.2", + "@tiptap/react": "3.32.2", + "@tiptap/starter-kit": "3.32.2", "i18next": "26.4.4", "leaflet": "1.9.4", "lucide-react": "1.56.0", diff --git a/apps/web/src/accounts/HouseholdSettings.tsx b/apps/web/src/accounts/HouseholdSettings.tsx new file mode 100644 index 0000000..db03c3b --- /dev/null +++ b/apps/web/src/accounts/HouseholdSettings.tsx @@ -0,0 +1,75 @@ +import { useEffect, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import type { Account } from '@tendly/shared'; +import { api, result } from './api.js'; + +export function HouseholdSettings({ + household, + run, + busy, +}: { + household: Account['households'][number]; + run: (action: () => Promise) => Promise; + busy: boolean; +}) { + const { t } = useTranslation(); + const [base, setBase] = useState(household); + const [name, setName] = useState(household.name); + const [timezone, setTimezone] = useState(household.timezone); + const dirty = name !== base.name || timezone !== base.timezone; + const remoteChanged = household.name !== base.name || household.timezone !== base.timezone; + useEffect(() => { + // Refetches may update the baseline only while no local draft would be lost. + if (remoteChanged && (!dirty || (name === household.name && timezone === household.timezone))) { + setBase(household); + setName(household.name); + setTimezone(household.timezone); + } + }, [household, remoteChanged, dirty, name, timezone]); + return ( +
{ + event.preventDefault(); + void run(() => + result( + api.PATCH('/api/v1/households/{id}', { + params: { path: { id: household.id } }, + body: { baseName: base.name, baseTimezone: base.timezone, name, timezone }, + }), + ), + ); + }} + > +
+ + +
+ + {remoteChanged && ( + + )} +
+
+
+ ); +} diff --git a/apps/web/src/accounts/Settings.tsx b/apps/web/src/accounts/Settings.tsx index 007bebd..83a0fa3 100644 --- a/apps/web/src/accounts/Settings.tsx +++ b/apps/web/src/accounts/Settings.tsx @@ -1,3 +1,4 @@ +import { HouseholdSettings } from './HouseholdSettings.js'; import { useState, type FormEvent } from 'react'; import { useTranslation } from 'react-i18next'; import { useQuery, useQueryClient } from '@tanstack/react-query'; @@ -10,6 +11,7 @@ import { enroll, errorKey, signIn, type EntryLink } from './Auth.js'; type Run = (action: () => Promise, message?: string) => Promise; export function Settings({ account, refresh, link, clearLink, useInvitation, embedded = false, activeHouseholdId }: { account: Account; refresh: () => Promise; link: EntryLink; clearLink: () => void; useInvitation: (code: string) => void; embedded?: boolean; activeHouseholdId?: string }) { const { t, i18n } = useTranslation(); + const version = useQuery({ queryKey: ['version'], queryFn:()=>result(api.GET('/api/v1/version')) }); const queries = useQueryClient(); const [page, setPage] = useState('account'); const [householdId, setHouseholdId] = useState(activeHouseholdId ?? account.households[0]?.id ?? ''); @@ -46,6 +48,7 @@ export function Settings({ account, refresh, link, clearLink, useInvitation, emb {page === 'account' && <>
} {page === 'members' && household && } {page === 'smtp' && account.deploymentAdmin && } + {version.data&&

Tendly · {version.data.version}

} ; } @@ -83,6 +86,7 @@ function MembersPanel({ household, run, busy }: { household: Account['households const members = useQuery({ queryKey: ['members', household.id], queryFn: () => result(api.GET('/api/v1/households/{id}/members', { params: { path: { id: household.id } } })) }); return <>

{household.name}

{household.timezone}

+ {household.role === 'admin' && } {members.isError &&

{t('network_error')}

}
    {members.data?.map((member) =>
  • {member.name}{member.email}
    diff --git a/apps/web/src/accounts/i18n.ts b/apps/web/src/accounts/i18n.ts index 8e889c9..b98a491 100644 --- a/apps/web/src/accounts/i18n.ts +++ b/apps/web/src/accounts/i18n.ts @@ -1,8 +1,11 @@ +import { viewCopy } from '../views/i18n.js'; +import { contentCopy } from '../content/i18n.js'; import { taskCopy } from '../tasks/i18n.js'; import i18n from 'i18next'; import { initReactI18next } from 'react-i18next'; const copy: Record = { ...taskCopy, + ...contentCopy, ...viewCopy, haveInvitationCode: ['Have an invitation code?', 'Har du en inbjudningskod?'], invitationCode: ['Invitation code', 'Inbjudningskod'], useInvitationCode: ['Use invitation code', 'Använd inbjudningskod'], diff --git a/apps/web/src/components/ui/dialog.tsx b/apps/web/src/components/ui/dialog.tsx index cae9c7b..ac79e39 100644 --- a/apps/web/src/components/ui/dialog.tsx +++ b/apps/web/src/components/ui/dialog.tsx @@ -4,15 +4,15 @@ import { X } from 'lucide-react'; import { useTranslation } from 'react-i18next'; // shadcn/ui's Radix composition: focus trapping, Escape and focus restoration live // in the primitive; Tendly supplies its responsive sheet treatment. -export function Dialog({ open, onOpenChange, title, children, sheet = false }: { - open: boolean; onOpenChange: (open: boolean) => void; title: string; children: ReactNode; sheet?: boolean; +export function Dialog({ open, onOpenChange, title, children, sheet = false, wide = false }: { + open: boolean; onOpenChange: (open: boolean) => void; title: string; children: ReactNode; sheet?: boolean; wide?: boolean; }) { const { t } = useTranslation(); const returnFocus = useRef(document.activeElement); return - { + { event.preventDefault(); const target = returnFocus.current; if (target instanceof HTMLElement && target.isConnected) target.focus(); diff --git a/apps/web/src/content/ContentPanel.tsx b/apps/web/src/content/ContentPanel.tsx new file mode 100644 index 0000000..6858142 --- /dev/null +++ b/apps/web/src/content/ContentPanel.tsx @@ -0,0 +1,446 @@ +import { useEffect, useId, useState } from 'react'; +import { useInfiniteQuery, useQuery, useQueryClient } from '@tanstack/react-query'; +import { useTranslation } from 'react-i18next'; +import { toDocument, documentSchema, plainText, type TaskFields } from '@tendly/shared'; +import { api, result } from '../accounts/api.js'; +import { RichEditor } from './RichEditor.js'; +import { uploadFiles } from './api.js'; +import { Dialog } from '../components/ui/dialog.js'; +import type { Member } from '../tasks/TaskFields.js'; +export function ContentPanel({ + householdId, + taskId, + userId, + members, +}: { + householdId: string; + taskId: string; + userId: string; + members: Member[]; +}) { + const { t, i18n } = useTranslation(); + const tabsId = useId(); + const queries = useQueryClient(); + const [contentValid, setContentValid] = useState(true); + const [tab, setTab] = useState<'comments' | 'activity'>('comments'); + const draftKey = `tendly-comment:${userId}:${householdId}:${taskId}`; + const [draft, setDraft] = useState(() => { + try { + const stored = sessionStorage.getItem(draftKey); + return stored ? documentSchema.parse(JSON.parse(stored).draft) : toDocument(''); + } catch { + return toDocument(''); + } + }); + const [editing, setEditing] = useState<{ + id: string; + version: number; + } | null>(() => { + try { + return JSON.parse(sessionStorage.getItem(draftKey) ?? '{}').editing ?? null; + } catch { + return null; + } + }); + useEffect(() => { + try { + if (plainText(draft).trim() || JSON.stringify(draft).includes('"image"')) + sessionStorage.setItem(draftKey, JSON.stringify({ draft, editing })); + else sessionStorage.removeItem(draftKey); + } catch { + /* Draft stays in memory if browser storage is unavailable. */ + } + }, [draftKey, draft, editing]); + const [undo, setUndo] = useState<{ id: string; version: number } | null>(null); + const [busy, setBusy] = useState(false), + [error, setError] = useState(''), + [preview, setPreview] = useState<{ + id: string; + name: string; + image: boolean; + } | null>(null); + const policy = useQuery({ + queryKey: ['planning', householdId, 'upload-policy'], + queryFn: () => + result( + api.GET('/api/v1/households/{householdId}/upload-policy', { + params: { path: { householdId } }, + }), + ), + }); + const path = { householdId, taskId }; + const comments = useInfiniteQuery({ + queryKey: ['planning', householdId, 'comments', taskId], + initialPageParam: 0, + queryFn: ({ pageParam }) => + result( + api.GET('/api/v1/households/{householdId}/tasks/{taskId}/comments', { + params: { path, query: { offset: pageParam } }, + }), + ), + getNextPageParam: (last) => last.nextOffset ?? undefined, + }); + const history = useInfiniteQuery({ + queryKey: ['planning', householdId, 'activity', taskId], + initialPageParam: 0, + enabled: tab === 'activity', + queryFn: ({ pageParam }) => + result( + api.GET('/api/v1/households/{householdId}/tasks/{taskId}/activity', { + params: { path, query: { offset: pageParam } }, + }), + ), + getNextPageParam: (last) => last.nextOffset ?? undefined, + }); + const files = useQuery({ + queryKey: ['planning', householdId, 'attachments', taskId], + queryFn: () => + result( + api.GET('/api/v1/households/{householdId}/tasks/{taskId}/attachments', { + params: { path }, + }), + ), + }); + const refresh = (key = 'comments') => + queries.invalidateQueries({ + queryKey: ['planning', householdId, key, taskId], + }); + const upload = async (selected: File[]) => { + setError(''); + try { + return await uploadFiles(householdId, taskId, selected); + } finally { + await refresh('attachments'); + } + }; + async function post() { + if (!contentValid) return; + setBusy(true); + setError(''); + try { + const body = { body: toDocument(draft) }; + if (editing) + await result( + api.PATCH('/api/v1/households/{householdId}/tasks/{taskId}/comments/{id}', { + params: { path: { ...path, id: editing.id } }, + body: { ...body, baseVersion: editing.version }, + }), + ); + else + await result( + api.POST('/api/v1/households/{householdId}/tasks/{taskId}/comments', { + params: { path }, + body, + }), + ); + setDraft((current) => + JSON.stringify(current) === JSON.stringify(draft) ? toDocument('') : current, + ); + setEditing(null); + await refresh(); + } catch (e) { + setError(e instanceof Error ? e.message : 'network_error'); + } finally { + setBusy(false); + } + } + async function remove(id: string, version: number, deleted: boolean) { + setBusy(true); + setError(''); + try { + const updated = await result( + api.PATCH('/api/v1/households/{householdId}/tasks/{taskId}/comments/{id}', { + params: { path: { ...path, id } }, + body: { baseVersion: version, deleted }, + }), + ); + setUndo(deleted ? { id, version: updated.version } : null); + await refresh(); + } catch (e) { + setError(e instanceof Error ? e.message : 'network_error'); + } finally { + setBusy(false); + } + } + const date = (v: string) => + new Intl.DateTimeFormat(i18n.language, { + dateStyle: 'medium', + timeStyle: 'short', + }).format(new Date(v)); + return ( +
    +

    {t('attachments')}

    +

    + {t('fileHelp', { + max: (policy.data?.maxBytes ?? 50_000_000) / 1_000_000, + })} +

    +
    + + +
    + {files.isError && ( +

    + {t('network_error')} +

    + )} +
      + {files.data?.map((f) => ( +
    • + {f.preview && ( + + )} + + {f.name} + {(f.size / 1_000_000).toFixed(1)} MB + + {(f.preview || f.mime === 'application/pdf') && ( + + )} + + {t('download')} + +
    • + ))} +
    +
    { + if (['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) { + event.preventDefault(); + const next = + event.key === 'Home' + ? 'comments' + : event.key === 'End' + ? 'activity' + : tab === 'comments' + ? 'activity' + : 'comments'; + setTab(next); + document.getElementById(tabsId + '-' + next)?.focus(); + } + }} + > + + +
    + {error && ( +
    + {t(error)} + {error === 'comment_conflict' && ( + + )} +
    + )} + {busy &&

    {t('saving')}

    } +
    + {tab === 'comments' ? ( + <> +
    + +
    + + {editing && ( + + )} +
    +
    + {undo && ( +

    + {t('commentDeleted')}{' '} + +

    + )} + {comments.isError && ( +

    + {t('network_error')}{' '} + +

    + )} + {comments.data?.pages + .flatMap((p) => p.items) + .map((c) => ( +
    +
    + {c.author} + + {c.updatedAt !== c.createdAt && ( + {t('edited')} + )} +
    + + {c.authorId === userId && ( +
    + + +
    + )} +
    + ))} + {comments.hasNextPage && ( + + )} + + ) : ( + <> + {history.isError && ( +

    + {t('network_error')}{' '} + +

    + )} +
      + {history.data?.pages + .flatMap((p) => p.items) + .map((a) => ( +
    1. + {a.author} ·{' '} + {a.fields + .map((f) => t(f === 'epicId' ? 'epic' : f === 'high' ? 'high' : f)) + .join(', ')} + +
    2. + ))} +
    + {history.hasNextPage && ( + + )} + + )} +
    + {preview && ( + { + if (!open) setPreview(null); + }} + > + {preview.image ? ( + {preview.name} + ) : ( +