From ef96d3cb5b85f866858110c3ae8c14ce4e4ed67b Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:35:03 +0000 Subject: [PATCH 01/16] feat(database): add archive, space order and dashboard page size fields --- .../0062_dashboard_library_tools.sql | 3 + .../migrations/meta/0062_snapshot.json | 6363 +++++++++++++++++ .../database/migrations/meta/_journal.json | 7 + packages/database/schema.ts | 13 + 4 files changed, 6386 insertions(+) create mode 100644 packages/database/migrations/0062_dashboard_library_tools.sql create mode 100644 packages/database/migrations/meta/0062_snapshot.json diff --git a/packages/database/migrations/0062_dashboard_library_tools.sql b/packages/database/migrations/0062_dashboard_library_tools.sql new file mode 100644 index 00000000000..3255005d04b --- /dev/null +++ b/packages/database/migrations/0062_dashboard_library_tools.sql @@ -0,0 +1,3 @@ +ALTER TABLE `space_videos` ADD `position` int;--> statement-breakpoint +ALTER TABLE `videos` ADD `archivedAt` timestamp;--> statement-breakpoint +CREATE INDEX `org_owner_folder_archived_effective_idx` ON `videos` (`orgId`,`ownerId`,`folderId`,`archivedAt`,`effectiveCreatedAt`); \ No newline at end of file diff --git a/packages/database/migrations/meta/0062_snapshot.json b/packages/database/migrations/meta/0062_snapshot.json new file mode 100644 index 00000000000..b4459960f41 --- /dev/null +++ b/packages/database/migrations/meta/0062_snapshot.json @@ -0,0 +1,6363 @@ +{ + "version": "5", + "dialect": "mysql", + "id": "ed3db4f5-17d1-4fa4-8d31-a2d5c1217e4d", + "prevId": "45632039-82de-46d3-b9b4-96c0a5a6b756", + "tables": { + "accounts": { + "name": "accounts", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "userId": { + "name": "userId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "provider": { + "name": "provider", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "providerAccountId": { + "name": "providerAccountId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "access_token": { + "name": "access_token", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_in": { + "name": "expires_in", + "type": "int", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "id_token": { + "name": "id_token", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "refresh_token": { + "name": "refresh_token", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "refresh_token_expires_in": { + "name": "refresh_token_expires_in", + "type": "int", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "token_type": { + "name": "token_type", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + }, + "tempColumn": { + "name": "tempColumn", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "user_id_idx": { + "name": "user_id_idx", + "columns": ["userId"], + "isUnique": false + }, + "provider_account_id_idx": { + "name": "provider_account_id_idx", + "columns": ["providerAccountId"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "accounts_id": { + "name": "accounts_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "agent_api_authorization_codes": { + "name": "agent_api_authorization_codes", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "userId": { + "name": "userId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "codeHash": { + "name": "codeHash", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "codeChallenge": { + "name": "codeChallenge", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "redirectUri": { + "name": "redirectUri", + "type": "varchar(512)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scopes": { + "name": "scopes", + "type": "json", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expiresAt": { + "name": "expiresAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "consumedAt": { + "name": "consumedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + } + }, + "indexes": { + "code_hash_idx": { + "name": "code_hash_idx", + "columns": ["codeHash"], + "isUnique": true + }, + "expires_at_idx": { + "name": "expires_at_idx", + "columns": ["expiresAt"], + "isUnique": false + }, + "user_created_at_idx": { + "name": "user_created_at_idx", + "columns": ["userId", "createdAt"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "agent_api_authorization_codes_id": { + "name": "agent_api_authorization_codes_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "agent_api_idempotency": { + "name": "agent_api_idempotency", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "userId": { + "name": "userId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "operation": { + "name": "operation", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "keyHash": { + "name": "keyHash", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "requestHash": { + "name": "requestHash", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "varchar(16)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "statusCode": { + "name": "statusCode", + "type": "int", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "response": { + "name": "response", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expiresAt": { + "name": "expiresAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": { + "user_operation_key_idx": { + "name": "user_operation_key_idx", + "columns": ["userId", "operation", "keyHash"], + "isUnique": true + }, + "expires_at_idx": { + "name": "expires_at_idx", + "columns": ["expiresAt"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "agent_api_idempotency_id": { + "name": "agent_api_idempotency_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "agent_api_keys": { + "name": "agent_api_keys", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "userId": { + "name": "userId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tokenHash": { + "name": "tokenHash", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "varchar(100)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'Cap CLI'" + }, + "scopes": { + "name": "scopes", + "type": "json", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expiresAt": { + "name": "expiresAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "revokedAt": { + "name": "revokedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "lastUsedAt": { + "name": "lastUsedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "token_hash_idx": { + "name": "token_hash_idx", + "columns": ["tokenHash"], + "isUnique": true + }, + "user_created_at_idx": { + "name": "user_created_at_idx", + "columns": ["userId", "createdAt"], + "isUnique": false + }, + "expires_at_idx": { + "name": "expires_at_idx", + "columns": ["expiresAt"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "agent_api_keys_id": { + "name": "agent_api_keys_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "agent_api_operations": { + "name": "agent_api_operations", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "userId": { + "name": "userId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "varchar(32)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "resourceId": { + "name": "resourceId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "resultResourceId": { + "name": "resultResourceId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "varchar(16)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'queued'" + }, + "payload": { + "name": "payload", + "type": "json", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "result": { + "name": "result", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "errorCode": { + "name": "errorCode", + "type": "varchar(64)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "errorMessage": { + "name": "errorMessage", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + }, + "completedAt": { + "name": "completedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "user_created_at_idx": { + "name": "user_created_at_idx", + "columns": ["userId", "createdAt"], + "isUnique": false + }, + "state_updated_at_idx": { + "name": "state_updated_at_idx", + "columns": ["state", "updatedAt"], + "isUnique": false + }, + "resource_id_idx": { + "name": "resource_id_idx", + "columns": ["resourceId"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "agent_api_operations_id": { + "name": "agent_api_operations_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "auth_api_keys": { + "name": "auth_api_keys", + "columns": { + "id": { + "name": "id", + "type": "varchar(36)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "userId": { + "name": "userId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "varchar(32)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'unknown'" + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + } + }, + "indexes": { + "user_id_created_at_idx": { + "name": "user_id_created_at_idx", + "columns": ["userId", "createdAt"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "auth_api_keys_id": { + "name": "auth_api_keys_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "comments": { + "name": "comments", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "varchar(6)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "timestamp": { + "name": "timestamp", + "type": "float", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "authorId": { + "name": "authorId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "videoId": { + "name": "videoId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + }, + "parentCommentId": { + "name": "parentCommentId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "mediaKey": { + "name": "mediaKey", + "type": "varchar(512)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "mediaDuration": { + "name": "mediaDuration", + "type": "float", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "mediaMeta": { + "name": "mediaMeta", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "video_type_created_idx": { + "name": "video_type_created_idx", + "columns": ["videoId", "type", "createdAt", "id"], + "isUnique": false + }, + "author_id_idx": { + "name": "author_id_idx", + "columns": ["authorId"], + "isUnique": false + }, + "parent_comment_id_idx": { + "name": "parent_comment_id_idx", + "columns": ["parentCommentId"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "comments_id": { + "name": "comments_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "developer_api_keys": { + "name": "developer_api_keys", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "appId": { + "name": "appId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "keyType": { + "name": "keyType", + "type": "varchar(8)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "keyPrefix": { + "name": "keyPrefix", + "type": "varchar(12)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "keyHash": { + "name": "keyHash", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "encryptedKey": { + "name": "encryptedKey", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "lastUsedAt": { + "name": "lastUsedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "revokedAt": { + "name": "revokedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + } + }, + "indexes": { + "key_hash_idx": { + "name": "key_hash_idx", + "columns": ["keyHash"], + "isUnique": true + }, + "app_key_type_idx": { + "name": "app_key_type_idx", + "columns": ["appId", "keyType"], + "isUnique": false + } + }, + "foreignKeys": { + "developer_api_keys_appId_developer_apps_id_fk": { + "name": "developer_api_keys_appId_developer_apps_id_fk", + "tableFrom": "developer_api_keys", + "tableTo": "developer_apps", + "columnsFrom": ["appId"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "developer_api_keys_id": { + "name": "developer_api_keys_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "developer_app_domains": { + "name": "developer_app_domains", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "appId": { + "name": "appId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "domain": { + "name": "domain", + "type": "varchar(253)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + } + }, + "indexes": {}, + "foreignKeys": { + "developer_app_domains_appId_developer_apps_id_fk": { + "name": "developer_app_domains_appId_developer_apps_id_fk", + "tableFrom": "developer_app_domains", + "tableTo": "developer_apps", + "columnsFrom": ["appId"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "developer_app_domains_id": { + "name": "developer_app_domains_id", + "columns": ["id"] + } + }, + "uniqueConstraints": { + "app_domain_unique": { + "name": "app_domain_unique", + "columns": ["appId", "domain"] + } + }, + "checkConstraint": {} + }, + "developer_apps": { + "name": "developer_apps", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ownerId": { + "name": "ownerId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "environment": { + "name": "environment", + "type": "varchar(16)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "logoUrl": { + "name": "logoUrl", + "type": "varchar(1024)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "deletedAt": { + "name": "deletedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": { + "owner_deleted_idx": { + "name": "owner_deleted_idx", + "columns": ["ownerId", "deletedAt"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "developer_apps_id": { + "name": "developer_apps_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "developer_credit_accounts": { + "name": "developer_credit_accounts", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "appId": { + "name": "appId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ownerId": { + "name": "ownerId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "balanceMicroCredits": { + "name": "balanceMicroCredits", + "type": "bigint unsigned", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "stripeCustomerId": { + "name": "stripeCustomerId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stripePaymentMethodId": { + "name": "stripePaymentMethodId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "autoTopUpEnabled": { + "name": "autoTopUpEnabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "autoTopUpThresholdMicroCredits": { + "name": "autoTopUpThresholdMicroCredits", + "type": "bigint unsigned", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "autoTopUpAmountCents": { + "name": "autoTopUpAmountCents", + "type": "int", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": { + "app_id_unique": { + "name": "app_id_unique", + "columns": ["appId"], + "isUnique": true + }, + "owner_idx": { + "name": "owner_idx", + "columns": ["ownerId"], + "isUnique": false + }, + "auto_top_up_idx": { + "name": "auto_top_up_idx", + "columns": ["autoTopUpEnabled"], + "isUnique": false + } + }, + "foreignKeys": { + "developer_credit_accounts_appId_developer_apps_id_fk": { + "name": "developer_credit_accounts_appId_developer_apps_id_fk", + "tableFrom": "developer_credit_accounts", + "tableTo": "developer_apps", + "columnsFrom": ["appId"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "developer_credit_accounts_id": { + "name": "developer_credit_accounts_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "developer_credit_transactions": { + "name": "developer_credit_transactions", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "accountId": { + "name": "accountId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "varchar(16)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "amountMicroCredits": { + "name": "amountMicroCredits", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "balanceAfterMicroCredits": { + "name": "balanceAfterMicroCredits", + "type": "bigint unsigned", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "referenceId": { + "name": "referenceId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "referenceType": { + "name": "referenceType", + "type": "varchar(32)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "metadata": { + "name": "metadata", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + } + }, + "indexes": { + "account_type_created_idx": { + "name": "account_type_created_idx", + "columns": ["accountId", "type", "createdAt"], + "isUnique": false + }, + "account_created_idx": { + "name": "account_created_idx", + "columns": ["accountId", "createdAt"], + "isUnique": false + }, + "account_ref_dedup_idx": { + "name": "account_ref_dedup_idx", + "columns": ["accountId", "referenceId", "referenceType"], + "isUnique": false + }, + "reference_type_id_idx": { + "name": "reference_type_id_idx", + "columns": ["referenceType", "referenceId"], + "isUnique": false + } + }, + "foreignKeys": { + "dev_credit_txn_account_fk": { + "name": "dev_credit_txn_account_fk", + "tableFrom": "developer_credit_transactions", + "tableTo": "developer_credit_accounts", + "columnsFrom": ["accountId"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "developer_credit_transactions_id": { + "name": "developer_credit_transactions_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "developer_daily_storage_snapshots": { + "name": "developer_daily_storage_snapshots", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "appId": { + "name": "appId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "snapshotDate": { + "name": "snapshotDate", + "type": "varchar(10)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "totalDurationMinutes": { + "name": "totalDurationMinutes", + "type": "float", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "videoCount": { + "name": "videoCount", + "type": "int", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "microCreditsCharged": { + "name": "microCreditsCharged", + "type": "bigint unsigned", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "processedAt": { + "name": "processedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + } + }, + "indexes": {}, + "foreignKeys": { + "developer_daily_storage_snapshots_appId_developer_apps_id_fk": { + "name": "developer_daily_storage_snapshots_appId_developer_apps_id_fk", + "tableFrom": "developer_daily_storage_snapshots", + "tableTo": "developer_apps", + "columnsFrom": ["appId"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "developer_daily_storage_snapshots_id": { + "name": "developer_daily_storage_snapshots_id", + "columns": ["id"] + } + }, + "uniqueConstraints": { + "app_date_unique": { + "name": "app_date_unique", + "columns": ["appId", "snapshotDate"] + } + }, + "checkConstraint": {} + }, + "developer_delivery_daily": { + "name": "developer_delivery_daily", + "columns": { + "appId": { + "name": "appId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "day": { + "name": "day", + "type": "date", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tier": { + "name": "tier", + "type": "varchar(8)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "seconds": { + "name": "seconds", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "bytes": { + "name": "bytes", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "requests": { + "name": "requests", + "type": "int", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "abandonedBytes": { + "name": "abandonedBytes", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "final": { + "name": "final", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "finalizedAt": { + "name": "finalizedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "day_idx": { + "name": "day_idx", + "columns": ["day"], + "isUnique": false + } + }, + "foreignKeys": { + "developer_delivery_daily_appId_developer_apps_id_fk": { + "name": "developer_delivery_daily_appId_developer_apps_id_fk", + "tableFrom": "developer_delivery_daily", + "tableTo": "developer_apps", + "columnsFrom": ["appId"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "developer_delivery_daily_appId_day_tier_pk": { + "name": "developer_delivery_daily_appId_day_tier_pk", + "columns": ["appId", "day", "tier"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "developer_delivery_log_files": { + "name": "developer_delivery_log_files", + "columns": { + "logFile": { + "name": "logFile", + "type": "varchar(191)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "etag": { + "name": "etag", + "type": "varchar(128)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "logHour": { + "name": "logHour", + "type": "datetime", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "parts": { + "name": "parts", + "type": "json", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "processedAt": { + "name": "processedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "log_hour_idx": { + "name": "log_hour_idx", + "columns": ["logHour"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "developer_delivery_log_files_logFile": { + "name": "developer_delivery_log_files_logFile", + "columns": ["logFile"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "developer_transcripts": { + "name": "developer_transcripts", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "appId": { + "name": "appId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "externalUserId": { + "name": "externalUserId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'Untitled'" + }, + "status": { + "name": "status", + "type": "varchar(16)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sourceType": { + "name": "sourceType", + "type": "varchar(8)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sourceUrl": { + "name": "sourceUrl", + "type": "varchar(2048)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "videoId": { + "name": "videoId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "requestedAt": { + "name": "requestedAt", + "type": "timestamp(3)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "s3Key": { + "name": "s3Key", + "type": "varchar(512)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resultKey": { + "name": "resultKey", + "type": "varchar(512)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sourceBytes": { + "name": "sourceBytes", + "type": "bigint unsigned", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "durationSeconds": { + "name": "durationSeconds", + "type": "float", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "requestedLanguage": { + "name": "requestedLanguage", + "type": "varchar(16)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "language": { + "name": "language", + "type": "varchar(16)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "text": { + "name": "text", + "type": "mediumtext", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "wordCount": { + "name": "wordCount", + "type": "int", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "reservedMicroCredits": { + "name": "reservedMicroCredits", + "type": "bigint unsigned", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "billedMicroCredits": { + "name": "billedMicroCredits", + "type": "bigint unsigned", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "errorCode": { + "name": "errorCode", + "type": "varchar(64)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "errorMessage": { + "name": "errorMessage", + "type": "varchar(512)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "metadata": { + "name": "metadata", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "runId": { + "name": "runId", + "type": "varchar(32)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "queuedAt": { + "name": "queuedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "startedAt": { + "name": "startedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "completedAt": { + "name": "completedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "deletedAt": { + "name": "deletedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": { + "dev_transcripts_app_list_idx": { + "name": "dev_transcripts_app_list_idx", + "columns": ["appId", "deletedAt", "createdAt", "id"], + "isUnique": false + }, + "dev_transcripts_app_user_idx": { + "name": "dev_transcripts_app_user_idx", + "columns": ["appId", "externalUserId", "createdAt"], + "isUnique": false + }, + "dev_transcripts_app_status_idx": { + "name": "dev_transcripts_app_status_idx", + "columns": ["appId", "status", "createdAt"], + "isUnique": false + }, + "dev_transcripts_status_updated_idx": { + "name": "dev_transcripts_status_updated_idx", + "columns": ["status", "updatedAt"], + "isUnique": false + }, + "dev_transcripts_app_completed_idx": { + "name": "dev_transcripts_app_completed_idx", + "columns": [ + "appId", + "status", + "completedAt", + "durationSeconds", + "billedMicroCredits" + ], + "isUnique": false + }, + "dev_transcripts_app_status_held_idx": { + "name": "dev_transcripts_app_status_held_idx", + "columns": [ + "appId", + "status", + "createdAt", + "deletedAt", + "reservedMicroCredits" + ], + "isUnique": false + }, + "dev_transcripts_app_video_idx": { + "name": "dev_transcripts_app_video_idx", + "columns": ["appId", "videoId", "requestedAt", "id"], + "isUnique": false + } + }, + "foreignKeys": { + "developer_transcripts_appId_developer_apps_id_fk": { + "name": "developer_transcripts_appId_developer_apps_id_fk", + "tableFrom": "developer_transcripts", + "tableTo": "developer_apps", + "columnsFrom": ["appId"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "developer_transcripts_id": { + "name": "developer_transcripts_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "developer_video_imports": { + "name": "developer_video_imports", + "columns": { + "videoId": { + "name": "videoId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "appId": { + "name": "appId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "keyId": { + "name": "keyId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sourceUrl": { + "name": "sourceUrl", + "type": "varchar(2048)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "varchar(16)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'downloading'" + }, + "bytes": { + "name": "bytes", + "type": "bigint unsigned", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "errorCode": { + "name": "errorCode", + "type": "varchar(32)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "startedAt": { + "name": "startedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "finishedAt": { + "name": "finishedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + } + }, + "indexes": { + "dev_imports_app_state_idx": { + "name": "dev_imports_app_state_idx", + "columns": ["appId", "state"], + "isUnique": false + }, + "dev_imports_key_created_idx": { + "name": "dev_imports_key_created_idx", + "columns": ["keyId", "createdAt"], + "isUnique": false + } + }, + "foreignKeys": { + "developer_video_imports_appId_developer_apps_id_fk": { + "name": "developer_video_imports_appId_developer_apps_id_fk", + "tableFrom": "developer_video_imports", + "tableTo": "developer_apps", + "columnsFrom": ["appId"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "developer_video_imports_videoId": { + "name": "developer_video_imports_videoId", + "columns": ["videoId"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "developer_videos": { + "name": "developer_videos", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "appId": { + "name": "appId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "externalUserId": { + "name": "externalUserId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'Untitled'" + }, + "duration": { + "name": "duration", + "type": "float", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "width": { + "name": "width", + "type": "int", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "height": { + "name": "height", + "type": "int", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "fps": { + "name": "fps", + "type": "int", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "s3Key": { + "name": "s3Key", + "type": "varchar(512)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "transcriptionStatus": { + "name": "transcriptionStatus", + "type": "varchar(16)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "metadata": { + "name": "metadata", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "varchar(16)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'uploading'" + }, + "playbackId": { + "name": "playbackId", + "type": "varchar(64)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "maxResolutionTier": { + "name": "maxResolutionTier", + "type": "varchar(8)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'1080p'" + }, + "renditions": { + "name": "renditions", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "storedBytes": { + "name": "storedBytes", + "type": "bigint unsigned", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "errorReason": { + "name": "errorReason", + "type": "varchar(512)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "processing": { + "name": "processing", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "storagePaidUntil": { + "name": "storagePaidUntil", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "deletedAt": { + "name": "deletedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "filesDeletedAt": { + "name": "filesDeletedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": { + "app_created_idx": { + "name": "app_created_idx", + "columns": ["appId", "createdAt"], + "isUnique": false + }, + "app_user_idx": { + "name": "app_user_idx", + "columns": ["appId", "externalUserId"], + "isUnique": false + }, + "app_deleted_idx": { + "name": "app_deleted_idx", + "columns": ["appId", "deletedAt"], + "isUnique": false + }, + "playback_id_idx": { + "name": "playback_id_idx", + "columns": ["playbackId"], + "isUnique": true + }, + "files_pending_idx": { + "name": "files_pending_idx", + "columns": ["filesDeletedAt", "deletedAt"], + "isUnique": false + }, + "app_storage_idx": { + "name": "app_storage_idx", + "columns": [ + "appId", + "deletedAt", + "status", + "maxResolutionTier", + "width", + "height", + "storagePaidUntil", + "duration", + "createdAt" + ], + "isUnique": false + }, + "first_month_due_idx": { + "name": "first_month_due_idx", + "columns": ["storagePaidUntil", "status", "createdAt"], + "isUnique": false + } + }, + "foreignKeys": { + "developer_videos_appId_developer_apps_id_fk": { + "name": "developer_videos_appId_developer_apps_id_fk", + "tableFrom": "developer_videos", + "tableTo": "developer_apps", + "columnsFrom": ["appId"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "developer_videos_id": { + "name": "developer_videos_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "developer_webhook_endpoints": { + "name": "developer_webhook_endpoints", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "appId": { + "name": "appId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "varchar(2048)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "secretPrefix": { + "name": "secretPrefix", + "type": "varchar(12)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "encryptedSecret": { + "name": "encryptedSecret", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "events": { + "name": "events", + "type": "json", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "disabledReason": { + "name": "disabledReason", + "type": "varchar(32)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lastDeliveryAt": { + "name": "lastDeliveryAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lastDeliveryStatus": { + "name": "lastDeliveryStatus", + "type": "varchar(16)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lastResponseStatus": { + "name": "lastResponseStatus", + "type": "int", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lastErrorCode": { + "name": "lastErrorCode", + "type": "varchar(32)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "consecutiveFailures": { + "name": "consecutiveFailures", + "type": "int", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "failingSince": { + "name": "failingSince", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "deletedAt": { + "name": "deletedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": { + "dev_webhooks_app_list_idx": { + "name": "dev_webhooks_app_list_idx", + "columns": ["appId", "deletedAt", "createdAt", "id"], + "isUnique": false + } + }, + "foreignKeys": { + "developer_webhook_endpoints_appId_developer_apps_id_fk": { + "name": "developer_webhook_endpoints_appId_developer_apps_id_fk", + "tableFrom": "developer_webhook_endpoints", + "tableTo": "developer_apps", + "columnsFrom": ["appId"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "developer_webhook_endpoints_id": { + "name": "developer_webhook_endpoints_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "directory_users": { + "name": "directory_users", + "columns": { + "id": { + "name": "id", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "organizationId": { + "name": "organizationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "directoryId": { + "name": "directoryId", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "userId": { + "name": "userId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": { + "directory_users_organization_id_idx": { + "name": "directory_users_organization_id_idx", + "columns": ["organizationId"], + "isUnique": false + }, + "directory_users_user_org_idx": { + "name": "directory_users_user_org_idx", + "columns": ["userId", "organizationId"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "directory_users_id": { + "name": "directory_users_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "folders": { + "name": "folders", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "color": { + "name": "color", + "type": "varchar(16)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'normal'" + }, + "public": { + "name": "public", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "settings": { + "name": "settings", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "organizationId": { + "name": "organizationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "createdById": { + "name": "createdById", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "parentId": { + "name": "parentId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "spaceId": { + "name": "spaceId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": { + "organization_id_idx": { + "name": "organization_id_idx", + "columns": ["organizationId"], + "isUnique": false + }, + "created_by_id_idx": { + "name": "created_by_id_idx", + "columns": ["createdById"], + "isUnique": false + }, + "parent_id_idx": { + "name": "parent_id_idx", + "columns": ["parentId"], + "isUnique": false + }, + "space_id_idx": { + "name": "space_id_idx", + "columns": ["spaceId"], + "isUnique": false + }, + "public_parent_id_idx": { + "name": "public_parent_id_idx", + "columns": ["public", "parentId"], + "isUnique": false + }, + "public_space_parent_id_idx": { + "name": "public_space_parent_id_idx", + "columns": ["public", "spaceId", "parentId"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "folders_id": { + "name": "folders_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "imported_videos": { + "name": "imported_videos", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "orgId": { + "name": "orgId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source_id": { + "name": "source_id", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "id_idx": { + "name": "id_idx", + "columns": ["id"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "imported_videos_orgId_source_source_id_pk": { + "name": "imported_videos_orgId_source_source_id_pk", + "columns": ["orgId", "source", "source_id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "integration_installations": { + "name": "integration_installations", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "provider": { + "name": "provider", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "externalId": { + "name": "externalId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "displayName": { + "name": "displayName", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "organizationId": { + "name": "organizationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "installedByUserId": { + "name": "installedByUserId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "encryptedCredentials": { + "name": "encryptedCredentials", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "metadata": { + "name": "metadata", + "type": "json", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": { + "provider_external_id_idx": { + "name": "provider_external_id_idx", + "columns": ["provider", "externalId"], + "isUnique": true + }, + "organization_provider_display_name_idx": { + "name": "organization_provider_display_name_idx", + "columns": ["organizationId", "provider", "displayName"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "integration_installations_id": { + "name": "integration_installations_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "loom_migration_imports": { + "name": "loom_migration_imports", + "columns": { + "videoId": { + "name": "videoId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "requestId": { + "name": "requestId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "datetime", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "loom_migration_imports_request_idx": { + "name": "loom_migration_imports_request_idx", + "columns": ["requestId"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "loom_migration_imports_videoId": { + "name": "loom_migration_imports_videoId", + "columns": ["videoId"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "loom_migration_requests": { + "name": "loom_migration_requests", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "organizationId": { + "name": "organizationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "activeOrganizationId": { + "name": "activeOrganizationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "requestedByUserId": { + "name": "requestedByUserId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "workspaceName": { + "name": "workspaceName", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "customerNote": { + "name": "customerNote", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "customerReply": { + "name": "customerReply", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "invitedAt": { + "name": "invitedAt", + "type": "datetime", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "varchar(32)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "capMessage": { + "name": "capMessage", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expectedVideoCount": { + "name": "expectedVideoCount", + "type": "int", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "importedVideoCount": { + "name": "importedVideoCount", + "type": "int", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "queuedVideoCount": { + "name": "queuedVideoCount", + "type": "int", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "activeImportCount": { + "name": "activeImportCount", + "type": "int", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "activeImportLeaseToken": { + "name": "activeImportLeaseToken", + "type": "varchar(36)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "activeImportLeaseUntil": { + "name": "activeImportLeaseUntil", + "type": "datetime", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lastOperatorUserId": { + "name": "lastOperatorUserId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lastOperatorAt": { + "name": "lastOperatorAt", + "type": "datetime", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "completedAt": { + "name": "completedAt", + "type": "datetime", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "datetime", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updatedAt": { + "name": "updatedAt", + "type": "datetime", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "loom_migration_active_org_idx": { + "name": "loom_migration_active_org_idx", + "columns": ["activeOrganizationId"], + "isUnique": true + }, + "loom_migration_org_created_idx": { + "name": "loom_migration_org_created_idx", + "columns": ["organizationId", "createdAt"], + "isUnique": false + }, + "loom_migration_status_created_idx": { + "name": "loom_migration_status_created_idx", + "columns": ["status", "createdAt"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "loom_migration_requests_id": { + "name": "loom_migration_requests_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "loops_sync_jobs": { + "name": "loops_sync_jobs", + "columns": { + "userId": { + "name": "userId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "revision": { + "name": "revision", + "type": "int", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "nextAttemptAt": { + "name": "nextAttemptAt", + "type": "datetime", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "leaseToken": { + "name": "leaseToken", + "type": "varchar(36)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "leaseUntil": { + "name": "leaseUntil", + "type": "datetime", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "failures": { + "name": "failures", + "type": "int", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "lastError": { + "name": "lastError", + "type": "varchar(64)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "profileHash": { + "name": "profileHash", + "type": "varchar(64)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "teammateJoinedAt": { + "name": "teammateJoinedAt", + "type": "datetime", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "syncedEmail": { + "name": "syncedEmail", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lastSyncedAt": { + "name": "lastSyncedAt", + "type": "datetime", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "loops_sync_due_idx": { + "name": "loops_sync_due_idx", + "columns": ["nextAttemptAt"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "loops_sync_jobs_userId": { + "name": "loops_sync_jobs_userId", + "columns": ["userId"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "mcp_oauth_clients": { + "name": "mcp_oauth_clients", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "clientId": { + "name": "clientId", + "type": "varchar(128)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "clientName": { + "name": "clientName", + "type": "varchar(100)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "redirectUris": { + "name": "redirectUris", + "type": "json", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "activatedAt": { + "name": "activatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + } + }, + "indexes": { + "client_id_idx": { + "name": "client_id_idx", + "columns": ["clientId"], + "isUnique": true + }, + "inactive_created_at_idx": { + "name": "inactive_created_at_idx", + "columns": ["activatedAt", "createdAt"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "mcp_oauth_clients_id": { + "name": "mcp_oauth_clients_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "mcp_oauth_codes": { + "name": "mcp_oauth_codes", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "userId": { + "name": "userId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "clientId": { + "name": "clientId", + "type": "varchar(128)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "codeHash": { + "name": "codeHash", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "codeChallenge": { + "name": "codeChallenge", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "redirectUri": { + "name": "redirectUri", + "type": "varchar(512)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "resource": { + "name": "resource", + "type": "varchar(512)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expiresAt": { + "name": "expiresAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "consumedAt": { + "name": "consumedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + } + }, + "indexes": { + "code_hash_idx": { + "name": "code_hash_idx", + "columns": ["codeHash"], + "isUnique": true + }, + "expires_at_idx": { + "name": "expires_at_idx", + "columns": ["expiresAt"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "mcp_oauth_codes_id": { + "name": "mcp_oauth_codes_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "mcp_oauth_registration_quotas": { + "name": "mcp_oauth_registration_quotas", + "columns": { + "windowId": { + "name": "windowId", + "type": "varchar(10)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "registrations": { + "name": "registrations", + "type": "int", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "expiresAt": { + "name": "expiresAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "expires_at_idx": { + "name": "expires_at_idx", + "columns": ["expiresAt"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "mcp_oauth_registration_quotas_windowId": { + "name": "mcp_oauth_registration_quotas_windowId", + "columns": ["windowId"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "mcp_oauth_tokens": { + "name": "mcp_oauth_tokens", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "userId": { + "name": "userId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "clientId": { + "name": "clientId", + "type": "varchar(128)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "familyId": { + "name": "familyId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "resource": { + "name": "resource", + "type": "varchar(512)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "accessHash": { + "name": "accessHash", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "refreshHash": { + "name": "refreshHash", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "accessExpiresAt": { + "name": "accessExpiresAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "refreshExpiresAt": { + "name": "refreshExpiresAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "revokedAt": { + "name": "revokedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + } + }, + "indexes": { + "access_hash_idx": { + "name": "access_hash_idx", + "columns": ["accessHash"], + "isUnique": true + }, + "refresh_hash_idx": { + "name": "refresh_hash_idx", + "columns": ["refreshHash"], + "isUnique": true + }, + "family_id_idx": { + "name": "family_id_idx", + "columns": ["familyId"], + "isUnique": false + }, + "client_active_idx": { + "name": "client_active_idx", + "columns": ["clientId", "revokedAt", "refreshExpiresAt"], + "isUnique": false + }, + "refresh_expires_at_idx": { + "name": "refresh_expires_at_idx", + "columns": ["refreshExpiresAt"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "mcp_oauth_tokens_id": { + "name": "mcp_oauth_tokens_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "media_processing_budgets": { + "name": "media_processing_budgets", + "columns": { + "id": { + "name": "id", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reserved_bytes": { + "name": "reserved_bytes", + "type": "bigint unsigned", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "limit_bytes": { + "name": "limit_bytes", + "type": "bigint unsigned", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "datetime(3)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "media_budget_expiry_idx": { + "name": "media_budget_expiry_idx", + "columns": ["expires_at"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "media_processing_budgets_id": { + "name": "media_processing_budgets_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "messenger_conversations": { + "name": "messenger_conversations", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "agent": { + "name": "agent", + "type": "varchar(32)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "mode": { + "name": "mode", + "type": "varchar(16)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'agent'" + }, + "userId": { + "name": "userId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "anonymousId": { + "name": "anonymousId", + "type": "varchar(64)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "takeoverByUserId": { + "name": "takeoverByUserId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "takeoverAt": { + "name": "takeoverAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + }, + "lastMessageAt": { + "name": "lastMessageAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + } + }, + "indexes": { + "user_last_message_idx": { + "name": "user_last_message_idx", + "columns": ["userId", "lastMessageAt"], + "isUnique": false + }, + "anonymous_last_message_idx": { + "name": "anonymous_last_message_idx", + "columns": ["anonymousId", "lastMessageAt"], + "isUnique": false + }, + "mode_last_message_idx": { + "name": "mode_last_message_idx", + "columns": ["mode", "lastMessageAt"], + "isUnique": false + }, + "updated_at_idx": { + "name": "updated_at_idx", + "columns": ["updatedAt"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "messenger_conversations_id": { + "name": "messenger_conversations_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "messenger_messages": { + "name": "messenger_messages", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "conversationId": { + "name": "conversationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "role": { + "name": "role", + "type": "varchar(16)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "userId": { + "name": "userId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "anonymousId": { + "name": "anonymousId", + "type": "varchar(64)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + } + }, + "indexes": { + "conversation_created_at_idx": { + "name": "conversation_created_at_idx", + "columns": ["conversationId", "createdAt"], + "isUnique": false + }, + "role_created_at_idx": { + "name": "role_created_at_idx", + "columns": ["role", "createdAt"], + "isUnique": false + } + }, + "foreignKeys": { + "messenger_messages_conversationId_messenger_conversations_id_fk": { + "name": "messenger_messages_conversationId_messenger_conversations_id_fk", + "tableFrom": "messenger_messages", + "tableTo": "messenger_conversations", + "columnsFrom": ["conversationId"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "messenger_messages_id": { + "name": "messenger_messages_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "messenger_support_emails": { + "name": "messenger_support_emails", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "conversationId": { + "name": "conversationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "userId": { + "name": "userId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "userEmail": { + "name": "userEmail", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "subject": { + "name": "subject", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + } + }, + "indexes": { + "support_email_user_created_at_idx": { + "name": "support_email_user_created_at_idx", + "columns": ["userId", "createdAt"], + "isUnique": false + }, + "support_email_conversation_created_at_idx": { + "name": "support_email_conversation_created_at_idx", + "columns": ["conversationId", "createdAt"], + "isUnique": false + } + }, + "foreignKeys": { + "support_email_conversation_fk": { + "name": "support_email_conversation_fk", + "tableFrom": "messenger_support_emails", + "tableTo": "messenger_conversations", + "columnsFrom": ["conversationId"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "messenger_support_emails_id": { + "name": "messenger_support_emails_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "mobile_push_claims": { + "name": "mobile_push_claims", + "columns": { + "id": { + "name": "id", + "type": "varchar(128)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + } + }, + "indexes": { + "created_at_idx": { + "name": "created_at_idx", + "columns": ["createdAt"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "mobile_push_claims_id": { + "name": "mobile_push_claims_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "mobile_push_tokens": { + "name": "mobile_push_tokens", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "userId": { + "name": "userId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "token": { + "name": "token", + "type": "varchar(200)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sessionHash": { + "name": "sessionHash", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "environment": { + "name": "environment", + "type": "varchar(10)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": { + "token_idx": { + "name": "token_idx", + "columns": ["token"], + "isUnique": true + }, + "user_id_idx": { + "name": "user_id_idx", + "columns": ["userId"], + "isUnique": false + }, + "session_hash_idx": { + "name": "session_hash_idx", + "columns": ["sessionHash"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "mobile_push_tokens_id": { + "name": "mobile_push_tokens_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "notifications": { + "name": "notifications", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "orgId": { + "name": "orgId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "recipientId": { + "name": "recipientId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "varchar(16)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "data": { + "name": "data", + "type": "json", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "videoId": { + "name": "videoId", + "type": "varchar(50)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "dedupKey": { + "name": "dedupKey", + "type": "varchar(128)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "readAt": { + "name": "readAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + } + }, + "indexes": { + "org_id_idx": { + "name": "org_id_idx", + "columns": ["orgId"], + "isUnique": false + }, + "type_idx": { + "name": "type_idx", + "columns": ["type"], + "isUnique": false + }, + "read_at_idx": { + "name": "read_at_idx", + "columns": ["readAt"], + "isUnique": false + }, + "created_at_idx": { + "name": "created_at_idx", + "columns": ["createdAt"], + "isUnique": false + }, + "recipient_read_idx": { + "name": "recipient_read_idx", + "columns": ["recipientId", "readAt"], + "isUnique": false + }, + "recipient_created_idx": { + "name": "recipient_created_idx", + "columns": ["recipientId", "createdAt"], + "isUnique": false + }, + "dedup_key_idx": { + "name": "dedup_key_idx", + "columns": ["dedupKey"], + "isUnique": true + }, + "type_recipient_created_idx": { + "name": "type_recipient_created_idx", + "columns": ["type", "recipientId", "createdAt"], + "isUnique": false + }, + "type_recipient_video_created_idx": { + "name": "type_recipient_video_created_idx", + "columns": ["type", "recipientId", "videoId", "createdAt"], + "isUnique": false + }, + "video_id_idx": { + "name": "video_id_idx", + "columns": ["videoId"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "notifications_id": { + "name": "notifications_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "organization_directory_sync": { + "name": "organization_directory_sync", + "columns": { + "organizationId": { + "name": "organizationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "requestedAt": { + "name": "requestedAt", + "type": "datetime", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "syncedAt": { + "name": "syncedAt", + "type": "datetime", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "leaseExpiresAt": { + "name": "leaseExpiresAt", + "type": "datetime", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lastError": { + "name": "lastError", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "heldRemovals": { + "name": "heldRemovals", + "type": "int", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "removalsApprovedAt": { + "name": "removalsApprovedAt", + "type": "datetime", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "organization_directory_sync_organizationId": { + "name": "organization_directory_sync_organizationId", + "columns": ["organizationId"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "organization_invites": { + "name": "organization_invites", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "organizationId": { + "name": "organizationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "invitedEmail": { + "name": "invitedEmail", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "invitedByUserId": { + "name": "invitedByUserId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "role": { + "name": "role", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + }, + "expiresAt": { + "name": "expiresAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "organization_id_idx": { + "name": "organization_id_idx", + "columns": ["organizationId"], + "isUnique": false + }, + "invited_email_idx": { + "name": "invited_email_idx", + "columns": ["invitedEmail"], + "isUnique": false + }, + "invited_by_user_id_idx": { + "name": "invited_by_user_id_idx", + "columns": ["invitedByUserId"], + "isUnique": false + }, + "status_idx": { + "name": "status_idx", + "columns": ["status"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "organization_invites_id": { + "name": "organization_invites_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "organization_members": { + "name": "organization_members", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "userId": { + "name": "userId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "organizationId": { + "name": "organizationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "role": { + "name": "role", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "hasProSeat": { + "name": "hasProSeat", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": { + "organization_id_idx": { + "name": "organization_id_idx", + "columns": ["organizationId"], + "isUnique": false + }, + "user_id_organization_id_idx": { + "name": "user_id_organization_id_idx", + "columns": ["userId", "organizationId"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "organization_members_id": { + "name": "organization_members_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "organization_sso": { + "name": "organization_sso", + "columns": { + "organizationId": { + "name": "organizationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "purchasedByUserId": { + "name": "purchasedByUserId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "stripeCustomerId": { + "name": "stripeCustomerId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stripeSubscriptionId": { + "name": "stripeSubscriptionId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stripePriceId": { + "name": "stripePriceId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "varchar(32)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'unpaid'" + }, + "paidThrough": { + "name": "paidThrough", + "type": "datetime", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "currentPeriodEnd": { + "name": "currentPeriodEnd", + "type": "datetime", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cancelAtPeriodEnd": { + "name": "cancelAtPeriodEnd", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "checkoutAttemptId": { + "name": "checkoutAttemptId", + "type": "varchar(36)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "checkoutCurrency": { + "name": "checkoutCurrency", + "type": "varchar(3)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "checkoutPriceId": { + "name": "checkoutPriceId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "checkoutSessionId": { + "name": "checkoutSessionId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "checkoutStartedAt": { + "name": "checkoutStartedAt", + "type": "datetime", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": { + "sso_stripe_subscription_id_idx": { + "name": "sso_stripe_subscription_id_idx", + "columns": ["stripeSubscriptionId"], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "organization_sso_organizationId": { + "name": "organization_sso_organizationId", + "columns": ["organizationId"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "organizations": { + "name": "organizations", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ownerId": { + "name": "ownerId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "metadata": { + "name": "metadata", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tombstoneAt": { + "name": "tombstoneAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "allowedEmailDomain": { + "name": "allowedEmailDomain", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "defaultVideoVisibility": { + "name": "defaultVideoVisibility", + "type": "varchar(7)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "customDomain": { + "name": "customDomain", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "domainVerified": { + "name": "domainVerified", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "settings": { + "name": "settings", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "iconUrl": { + "name": "iconUrl", + "type": "varchar(1024)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "shareableLinkIconUrl": { + "name": "shareableLinkIconUrl", + "type": "varchar(1024)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + }, + "workosOrganizationId": { + "name": "workosOrganizationId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "workosConnectionId": { + "name": "workosConnectionId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "owner_id_tombstone_idx": { + "name": "owner_id_tombstone_idx", + "columns": ["ownerId", "tombstoneAt"], + "isUnique": false + }, + "custom_domain_idx": { + "name": "custom_domain_idx", + "columns": ["customDomain"], + "isUnique": false + }, + "workos_organization_id_idx": { + "name": "workos_organization_id_idx", + "columns": ["workosOrganizationId"], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "organizations_id": { + "name": "organizations_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "s3_buckets": { + "name": "s3_buckets", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ownerId": { + "name": "ownerId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "organizationId": { + "name": "organizationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "region": { + "name": "region", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "endpoint": { + "name": "endpoint", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "bucketName": { + "name": "bucketName", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "accessKeyId": { + "name": "accessKeyId", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "secretAccessKey": { + "name": "secretAccessKey", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "('aws')" + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": { + "owner_organization_idx": { + "name": "owner_organization_idx", + "columns": ["ownerId", "organizationId"], + "isUnique": false + }, + "organization_id_idx": { + "name": "organization_id_idx", + "columns": ["organizationId"], + "isUnique": false + }, + "organization_active_idx": { + "name": "organization_active_idx", + "columns": ["organizationId", "active", "updatedAt"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "s3_buckets_id": { + "name": "s3_buckets_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "sessions": { + "name": "sessions", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sessionToken": { + "name": "sessionToken", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "userId": { + "name": "userId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires": { + "name": "expires", + "type": "datetime", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": { + "session_token_idx": { + "name": "session_token_idx", + "columns": ["sessionToken"], + "isUnique": true + }, + "user_id_idx": { + "name": "user_id_idx", + "columns": ["userId"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "sessions_id": { + "name": "sessions_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "shared_videos": { + "name": "shared_videos", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "videoId": { + "name": "videoId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "folderId": { + "name": "folderId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "organizationId": { + "name": "organizationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sharedByUserId": { + "name": "sharedByUserId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sharedAt": { + "name": "sharedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + } + }, + "indexes": { + "folder_id_idx": { + "name": "folder_id_idx", + "columns": ["folderId"], + "isUnique": false + }, + "organization_id_idx": { + "name": "organization_id_idx", + "columns": ["organizationId"], + "isUnique": false + }, + "shared_by_user_id_idx": { + "name": "shared_by_user_id_idx", + "columns": ["sharedByUserId"], + "isUnique": false + }, + "video_id_organization_id_idx": { + "name": "video_id_organization_id_idx", + "columns": ["videoId", "organizationId"], + "isUnique": false + }, + "video_id_folder_id_idx": { + "name": "video_id_folder_id_idx", + "columns": ["videoId", "folderId"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "shared_videos_id": { + "name": "shared_videos_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "signed_baas": { + "name": "signed_baas", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "organizationId": { + "name": "organizationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "userId": { + "name": "userId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "stripeSubscriptionId": { + "name": "stripeSubscriptionId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "entityName": { + "name": "entityName", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "entityType": { + "name": "entityType", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "entityAddress": { + "name": "entityAddress", + "type": "varchar(500)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "signerName": { + "name": "signerName", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "signerTitle": { + "name": "signerTitle", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "noticesEmail": { + "name": "noticesEmail", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "signatureData": { + "name": "signatureData", + "type": "longtext", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "signedAt": { + "name": "signedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "emailSentAt": { + "name": "emailSentAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": { + "signed_baa_organization_id_idx": { + "name": "signed_baa_organization_id_idx", + "columns": ["organizationId"], + "isUnique": true + }, + "signed_baa_stripe_subscription_idx": { + "name": "signed_baa_stripe_subscription_idx", + "columns": ["stripeSubscriptionId"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "signed_baas_id": { + "name": "signed_baas_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "space_members": { + "name": "space_members", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "spaceId": { + "name": "spaceId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "userId": { + "name": "userId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "role": { + "name": "role", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'member'" + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": { + "user_id_idx": { + "name": "user_id_idx", + "columns": ["userId"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "space_members_id": { + "name": "space_members_id", + "columns": ["id"] + } + }, + "uniqueConstraints": { + "space_id_user_id_unique": { + "name": "space_id_user_id_unique", + "columns": ["spaceId", "userId"] + } + }, + "checkConstraint": {} + }, + "space_videos": { + "name": "space_videos", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "spaceId": { + "name": "spaceId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "folderId": { + "name": "folderId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "videoId": { + "name": "videoId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "addedById": { + "name": "addedById", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "addedAt": { + "name": "addedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "position": { + "name": "position", + "type": "int", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "folder_id_idx": { + "name": "folder_id_idx", + "columns": ["folderId"], + "isUnique": false + }, + "video_id_idx": { + "name": "video_id_idx", + "columns": ["videoId"], + "isUnique": false + }, + "added_by_id_idx": { + "name": "added_by_id_idx", + "columns": ["addedById"], + "isUnique": false + }, + "space_id_video_id_idx": { + "name": "space_id_video_id_idx", + "columns": ["spaceId", "videoId"], + "isUnique": false + }, + "space_id_folder_id_idx": { + "name": "space_id_folder_id_idx", + "columns": ["spaceId", "folderId"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "space_videos_id": { + "name": "space_videos_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "spaces": { + "name": "spaces", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "primary": { + "name": "primary", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "name": { + "name": "name", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "organizationId": { + "name": "organizationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "createdById": { + "name": "createdById", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "iconUrl": { + "name": "iconUrl", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "varchar(1000)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "settings": { + "name": "settings", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + }, + "privacy": { + "name": "privacy", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'Private'" + }, + "public": { + "name": "public", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + } + }, + "indexes": { + "organization_id_idx": { + "name": "organization_id_idx", + "columns": ["organizationId"], + "isUnique": false + }, + "created_by_id_idx": { + "name": "created_by_id_idx", + "columns": ["createdById"], + "isUnique": false + }, + "public_organization_id_idx": { + "name": "public_organization_id_idx", + "columns": ["public", "organizationId"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "spaces_id": { + "name": "spaces_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "storage_integrations": { + "name": "storage_integrations", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ownerId": { + "name": "ownerId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "organizationId": { + "name": "organizationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "provider": { + "name": "provider", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "displayName": { + "name": "displayName", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "varchar(32)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'active'" + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "encryptedConfig": { + "name": "encryptedConfig", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "googleDriveAccessToken": { + "name": "googleDriveAccessToken", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "googleDriveAccessTokenExpiresAt": { + "name": "googleDriveAccessTokenExpiresAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "googleDriveTokenRefreshLeaseId": { + "name": "googleDriveTokenRefreshLeaseId", + "type": "varchar(64)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "googleDriveTokenRefreshLeaseExpiresAt": { + "name": "googleDriveTokenRefreshLeaseExpiresAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "googleDriveStorageQuotaCache": { + "name": "googleDriveStorageQuotaCache", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": { + "owner_provider_idx": { + "name": "owner_provider_idx", + "columns": ["ownerId", "provider"], + "isUnique": false + }, + "owner_active_idx": { + "name": "owner_active_idx", + "columns": ["ownerId", "active"], + "isUnique": false + }, + "organization_provider_idx": { + "name": "organization_provider_idx", + "columns": ["organizationId", "provider"], + "isUnique": false + }, + "organization_active_idx": { + "name": "organization_active_idx", + "columns": ["organizationId", "active", "status"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "storage_integrations_id": { + "name": "storage_integrations_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "storage_objects": { + "name": "storage_objects", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "integrationId": { + "name": "integrationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ownerId": { + "name": "ownerId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "videoId": { + "name": "videoId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "objectKey": { + "name": "objectKey", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "objectKeyHash": { + "name": "objectKeyHash", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "providerObjectId": { + "name": "providerObjectId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "uploadSessionUrl": { + "name": "uploadSessionUrl", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "uploadStatus": { + "name": "uploadStatus", + "type": "varchar(32)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "contentType": { + "name": "contentType", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "contentLength": { + "name": "contentLength", + "type": "bigint unsigned", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "metadata": { + "name": "metadata", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": { + "integration_key_hash_idx": { + "name": "integration_key_hash_idx", + "columns": ["integrationId", "objectKeyHash"], + "isUnique": true + }, + "integration_status_idx": { + "name": "integration_status_idx", + "columns": ["integrationId", "uploadStatus"], + "isUnique": false + }, + "integration_object_key_prefix_idx": { + "name": "integration_object_key_prefix_idx", + "columns": ["integrationId", "`objectKey`(191)"], + "isUnique": false + }, + "video_id_idx": { + "name": "video_id_idx", + "columns": ["videoId"], + "isUnique": false + }, + "owner_id_idx": { + "name": "owner_id_idx", + "columns": ["ownerId"], + "isUnique": false + } + }, + "foreignKeys": { + "storage_objects_integrationId_storage_integrations_id_fk": { + "name": "storage_objects_integrationId_storage_integrations_id_fk", + "tableFrom": "storage_objects", + "tableTo": "storage_integrations", + "columnsFrom": ["integrationId"], + "columnsTo": ["id"], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "storage_objects_id": { + "name": "storage_objects_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "users": { + "name": "users", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lastName": { + "name": "lastName", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "emailVerified": { + "name": "emailVerified", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "image": { + "name": "image", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stripeCustomerId": { + "name": "stripeCustomerId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stripeSubscriptionId": { + "name": "stripeSubscriptionId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "thirdPartyStripeSubscriptionId": { + "name": "thirdPartyStripeSubscriptionId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stripeSubscriptionStatus": { + "name": "stripeSubscriptionStatus", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stripeSubscriptionPriceId": { + "name": "stripeSubscriptionPriceId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "preferences": { + "name": "preferences", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "default": "('null')" + }, + "activeOrganizationId": { + "name": "activeOrganizationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + }, + "onboardingSteps": { + "name": "onboardingSteps", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "onboarding_completed_at": { + "name": "onboarding_completed_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "customBucket": { + "name": "customBucket", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "inviteQuota": { + "name": "inviteQuota", + "type": "int", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "defaultOrgId": { + "name": "defaultOrgId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "authSessionVersion": { + "name": "authSessionVersion", + "type": "int", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "marketingOrigin": { + "name": "marketingOrigin", + "type": "varchar(20)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'unknown'" + } + }, + "indexes": { + "email_idx": { + "name": "email_idx", + "columns": ["email"], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "users_id": { + "name": "users_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "verification_tokens": { + "name": "verification_tokens", + "columns": { + "identifier": { + "name": "identifier", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "token": { + "name": "token", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires": { + "name": "expires", + "type": "datetime", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "verification_tokens_identifier": { + "name": "verification_tokens_identifier", + "columns": ["identifier"] + } + }, + "uniqueConstraints": { + "verification_tokens_token_unique": { + "name": "verification_tokens_token_unique", + "columns": ["token"] + } + }, + "checkConstraint": {} + }, + "video_edits": { + "name": "video_edits", + "columns": { + "videoId": { + "name": "videoId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sourceKey": { + "name": "sourceKey", + "type": "varchar(512)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "editSpec": { + "name": "editSpec", + "type": "json", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + } + }, + "indexes": {}, + "foreignKeys": { + "video_edits_videoId_videos_id_fk": { + "name": "video_edits_videoId_videos_id_fk", + "tableFrom": "video_edits", + "tableTo": "videos", + "columnsFrom": ["videoId"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "video_edits_videoId": { + "name": "video_edits_videoId", + "columns": ["videoId"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "video_processing_jobs": { + "name": "video_processing_jobs", + "columns": { + "video_id": { + "name": "video_id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "owner_id": { + "name": "owner_id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "generation": { + "name": "generation", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "manifest_sha256": { + "name": "manifest_sha256", + "type": "varchar(64)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "varchar(32)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'committing'" + }, + "attempt_id": { + "name": "attempt_id", + "type": "varchar(64)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "attempt_count": { + "name": "attempt_count", + "type": "int", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "lease_expires_at": { + "name": "lease_expires_at", + "type": "datetime(3)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "next_retry_at": { + "name": "next_retry_at", + "type": "datetime(3)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "workflow_run_id": { + "name": "workflow_run_id", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "remote_job_id": { + "name": "remote_job_id", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "verification": { + "name": "verification", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "output": { + "name": "output", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error_code": { + "name": "error_code", + "type": "varchar(64)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "datetime(3)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "datetime(3)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "processing_state_retry_video_idx": { + "name": "processing_state_retry_video_idx", + "columns": ["state", "next_retry_at", "video_id"], + "isUnique": false + }, + "processing_state_lease_video_idx": { + "name": "processing_state_lease_video_idx", + "columns": ["state", "lease_expires_at", "video_id"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "video_processing_jobs_video_id": { + "name": "video_processing_jobs_video_id", + "columns": ["video_id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "video_uploads": { + "name": "video_uploads", + "columns": { + "video_id": { + "name": "video_id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "uploaded": { + "name": "uploaded", + "type": "bigint unsigned", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "total": { + "name": "total", + "type": "bigint unsigned", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "mode": { + "name": "mode", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "phase": { + "name": "phase", + "type": "varchar(32)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'uploading'" + }, + "processing_progress": { + "name": "processing_progress", + "type": "int", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "processing_message": { + "name": "processing_message", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "processing_error": { + "name": "processing_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "raw_file_key": { + "name": "raw_file_key", + "type": "varchar(512)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "phase_updated_at_video_id_idx": { + "name": "phase_updated_at_video_id_idx", + "columns": ["phase", "updated_at", "video_id"], + "isUnique": false + }, + "started_at_idx": { + "name": "started_at_idx", + "columns": ["started_at"], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "video_uploads_video_id": { + "name": "video_uploads_video_id", + "columns": ["video_id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "video_viewer_grants": { + "name": "video_viewer_grants", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "videoId": { + "name": "videoId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "invitedByUserId": { + "name": "invitedByUserId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "revokedAt": { + "name": "revokedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "video_email_idx": { + "name": "video_email_idx", + "columns": ["videoId", "email"], + "isUnique": true + } + }, + "foreignKeys": { + "video_viewer_grants_videoId_videos_id_fk": { + "name": "video_viewer_grants_videoId_videos_id_fk", + "tableFrom": "video_viewer_grants", + "tableTo": "videos", + "columnsFrom": ["videoId"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "video_viewer_grants_id": { + "name": "video_viewer_grants_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + }, + "videos": { + "name": "videos", + "columns": { + "id": { + "name": "id", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ownerId": { + "name": "ownerId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "orgId": { + "name": "orgId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'My Video'" + }, + "bucket": { + "name": "bucket", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "storageIntegrationId": { + "name": "storageIntegrationId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "duration": { + "name": "duration", + "type": "float", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "width": { + "name": "width", + "type": "int", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "height": { + "name": "height", + "type": "int", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "fps": { + "name": "fps", + "type": "int", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "metadata": { + "name": "metadata", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "public": { + "name": "public", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "settings": { + "name": "settings", + "type": "json", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "transcriptionStatus": { + "name": "transcriptionStatus", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "json", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "('{\"type\":\"MediaConvert\"}')" + }, + "folderId": { + "name": "folderId", + "type": "varchar(15)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "createdAt": { + "name": "createdAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(now())" + }, + "effectiveCreatedAt": { + "name": "effectiveCreatedAt", + "type": "datetime", + "primaryKey": false, + "notNull": false, + "autoincrement": false, + "generated": { + "as": "COALESCE(\n STR_TO_DATE(JSON_UNQUOTE(JSON_EXTRACT(`metadata`, '$.customCreatedAt')), '%Y-%m-%dT%H:%i:%s.%fZ'),\n STR_TO_DATE(JSON_UNQUOTE(JSON_EXTRACT(`metadata`, '$.customCreatedAt')), '%Y-%m-%dT%H:%i:%sZ'),\n `createdAt`\n )", + "type": "stored" + } + }, + "updatedAt": { + "name": "updatedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "onUpdate": true, + "default": "(now())" + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "xStreamInfo": { + "name": "xStreamInfo", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "firstViewEmailSentAt": { + "name": "firstViewEmailSentAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "isScreenshot": { + "name": "isScreenshot", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "archivedAt": { + "name": "archivedAt", + "type": "timestamp", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "awsRegion": { + "name": "awsRegion", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "awsBucket": { + "name": "awsBucket", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "videoStartTime": { + "name": "videoStartTime", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "audioStartTime": { + "name": "audioStartTime", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "jobId": { + "name": "jobId", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "jobStatus": { + "name": "jobStatus", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "skipProcessing": { + "name": "skipProcessing", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + } + }, + "indexes": { + "owner_id_idx": { + "name": "owner_id_idx", + "columns": ["ownerId"], + "isUnique": false + }, + "owner_updated_id_idx": { + "name": "owner_updated_id_idx", + "columns": ["ownerId", "updatedAt", "id"], + "isUnique": false + }, + "is_public_idx": { + "name": "is_public_idx", + "columns": ["public"], + "isUnique": false + }, + "folder_id_idx": { + "name": "folder_id_idx", + "columns": ["folderId"], + "isUnique": false + }, + "storage_integration_id_idx": { + "name": "storage_integration_id_idx", + "columns": ["storageIntegrationId"], + "isUnique": false + }, + "org_owner_folder_idx": { + "name": "org_owner_folder_idx", + "columns": ["orgId", "ownerId", "folderId"], + "isUnique": false + }, + "org_owner_folder_effective_idx": { + "name": "org_owner_folder_effective_idx", + "columns": ["orgId", "ownerId", "folderId", "effectiveCreatedAt"], + "isUnique": false + }, + "org_effective_created_idx": { + "name": "org_effective_created_idx", + "columns": ["orgId", "effectiveCreatedAt"], + "isUnique": false + }, + "org_owner_folder_archived_effective_idx": { + "name": "org_owner_folder_archived_effective_idx", + "columns": [ + "orgId", + "ownerId", + "folderId", + "archivedAt", + "effectiveCreatedAt" + ], + "isUnique": false + }, + "screenshot_transcription_created_idx": { + "name": "screenshot_transcription_created_idx", + "columns": ["isScreenshot", "transcriptionStatus", "createdAt"], + "isUnique": false + } + }, + "foreignKeys": { + "videos_storageIntegrationId_storage_integrations_id_fk": { + "name": "videos_storageIntegrationId_storage_integrations_id_fk", + "tableFrom": "videos", + "tableTo": "storage_integrations", + "columnsFrom": ["storageIntegrationId"], + "columnsTo": ["id"], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "videos_id": { + "name": "videos_id", + "columns": ["id"] + } + }, + "uniqueConstraints": {}, + "checkConstraint": {} + } + }, + "views": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "tables": {}, + "indexes": { + "integration_object_key_prefix_idx": { + "columns": { + "`objectKey`(191)": { + "isExpression": true + } + } + } + } + } +} diff --git a/packages/database/migrations/meta/_journal.json b/packages/database/migrations/meta/_journal.json index c689b934826..d392856adbd 100644 --- a/packages/database/migrations/meta/_journal.json +++ b/packages/database/migrations/meta/_journal.json @@ -435,6 +435,13 @@ "when": 1794582375191, "tag": "0061_developer_delivery_metering", "breakpoints": true + }, + { + "idx": 62, + "version": "5", + "when": 1794867892168, + "tag": "0062_dashboard_library_tools", + "breakpoints": true } ] } diff --git a/packages/database/schema.ts b/packages/database/schema.ts index 9fc6d3ff653..8427b8582e2 100644 --- a/packages/database/schema.ts +++ b/packages/database/schema.ts @@ -119,6 +119,9 @@ export const users = mysqlTable( trackedEvents?: { user_signed_up?: boolean; }; + dashboard?: { + pageSize?: number; + }; } | null>() .default(null), activeOrganizationId: nanoId( @@ -543,6 +546,7 @@ export const videos = mysqlTable( xStreamInfo: text("xStreamInfo"), firstViewEmailSentAt: timestamp("firstViewEmailSentAt"), isScreenshot: boolean("isScreenshot").notNull().default(false), + archivedAt: timestamp("archivedAt"), // DEPRECATED awsRegion: varchar("awsRegion", { length: 255 }), awsBucket: varchar("awsBucket", { length: 255 }), @@ -573,6 +577,13 @@ export const videos = mysqlTable( table.orgId, table.effectiveCreatedAt, ), + index("org_owner_folder_archived_effective_idx").on( + table.orgId, + table.ownerId, + table.folderId, + table.archivedAt, + table.effectiveCreatedAt, + ), index("screenshot_transcription_created_idx").on( table.isScreenshot, table.transcriptionStatus, @@ -1501,6 +1512,7 @@ export const spaces = mysqlTable( disableTranscript?: boolean; disableComments?: boolean; publicPage?: PublicCollection.PublicPageSettings; + videoOrder?: "newest" | "oldest" | "custom"; }>(), password: encryptedTextNullable("password"), createdAt: timestamp("createdAt").notNull().defaultNow(), @@ -1554,6 +1566,7 @@ export const spaceVideos = mysqlTable( videoId: nanoId("videoId").notNull().$type(), addedById: nanoId("addedById").notNull().$type(), addedAt: timestamp("addedAt").notNull().defaultNow(), + position: int("position"), }, (table) => ({ folderIdIndex: index("folder_id_idx").on(table.folderId), From faf26719f09d3d67ed4d4e8e84c7df40a0526faf Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:35:03 +0000 Subject: [PATCH 02/16] feat(web): range select, select all, page size and archive in My Caps --- apps/web/actions/caps/list-view-ids.ts | 88 ++++ apps/web/actions/caps/page-size.ts | 27 ++ apps/web/actions/videos/archive.ts | 52 +++ .../dashboard/_components/dashboard-titles.ts | 4 + apps/web/app/(org)/dashboard/caps/Caps.tsx | 227 +++++++--- .../(org)/dashboard/caps/archived/page.tsx | 15 + .../(org)/dashboard/caps/caps-page-data.tsx | 404 ++++++++++++++++++ .../caps/components/CapCard/CapCard.tsx | 84 +++- .../caps/components/CapListHeader.tsx | 153 +++++++ .../caps/components/MoveItemsDialog.tsx | 21 +- .../caps/components/SelectedCapsBar.tsx | 68 ++- .../caps/components/useArchiveCaps.ts | 70 +++ .../caps/components/useCapSelection.ts | 158 +++++++ apps/web/app/(org)/dashboard/caps/page.tsx | 354 +-------------- .../[id]/components/FolderVideosSection.tsx | 91 ++-- apps/web/lib/cap-selection.ts | 89 ++++ apps/web/lib/dashboard-page-size.ts | 35 ++ apps/web/lib/folder.ts | 5 +- apps/web/lib/select-all-view.ts | 7 + apps/web/lib/video-archive.ts | 8 + 20 files changed, 1492 insertions(+), 468 deletions(-) create mode 100644 apps/web/actions/caps/list-view-ids.ts create mode 100644 apps/web/actions/caps/page-size.ts create mode 100644 apps/web/actions/videos/archive.ts create mode 100644 apps/web/app/(org)/dashboard/caps/archived/page.tsx create mode 100644 apps/web/app/(org)/dashboard/caps/caps-page-data.tsx create mode 100644 apps/web/app/(org)/dashboard/caps/components/CapListHeader.tsx create mode 100644 apps/web/app/(org)/dashboard/caps/components/useArchiveCaps.ts create mode 100644 apps/web/app/(org)/dashboard/caps/components/useCapSelection.ts create mode 100644 apps/web/lib/cap-selection.ts create mode 100644 apps/web/lib/dashboard-page-size.ts create mode 100644 apps/web/lib/select-all-view.ts create mode 100644 apps/web/lib/video-archive.ts diff --git a/apps/web/actions/caps/list-view-ids.ts b/apps/web/actions/caps/list-view-ids.ts new file mode 100644 index 00000000000..cddba3cb5a7 --- /dev/null +++ b/apps/web/actions/caps/list-view-ids.ts @@ -0,0 +1,88 @@ +"use server"; + +import { db } from "@cap/database"; +import { getCurrentUser } from "@cap/database/auth/session"; +import { + organizations, + sharedVideos, + spaceVideos, + videos, +} from "@cap/database/schema"; +import type { Organisation, Space, Video } from "@cap/web-domain"; +import { and, eq, isNotNull, isNull } from "drizzle-orm"; +import { getOrganizationAccess } from "@/actions/organization/authorization"; +import { getSpaceAccess } from "@/actions/organization/space-authorization"; +import { canManageOrganizationMembers } from "@/lib/permissions/roles"; +import { + MAX_SELECT_ALL_ITEMS, + type SelectAllView, +} from "@/lib/select-all-view"; + +// Returns the ids behind "Select all N" for the exact list the page shows, so a +// bulk action can run past the current page. The same filters as the page +// queries apply, and shared lists require the same rights that let the page +// show selection at all. +export async function listCapIdsInView( + view: SelectAllView, +): Promise { + const user = await getCurrentUser(); + if (!user) throw new Error("Unauthorized"); + + if (view.type === "personal" || view.type === "archived") { + if (!user.activeOrganizationId) return []; + const rows = await db() + .select({ id: videos.id }) + .from(videos) + .innerJoin(organizations, eq(videos.orgId, organizations.id)) + .where( + and( + eq(videos.ownerId, user.id), + eq(videos.orgId, user.activeOrganizationId), + isNull(organizations.tombstoneAt), + view.type === "personal" + ? and(isNull(videos.folderId), isNull(videos.archivedAt)) + : isNotNull(videos.archivedAt), + ), + ) + .limit(MAX_SELECT_ALL_ITEMS); + return rows.map((row) => row.id); + } + + if (view.type === "space") { + const access = await getSpaceAccess(user.id, view.spaceId as Space.SpaceId); + if (!access?.canManage) throw new Error("Forbidden"); + const rows = await db() + .selectDistinct({ id: videos.id }) + .from(spaceVideos) + .innerJoin(videos, eq(spaceVideos.videoId, videos.id)) + .leftJoin(organizations, eq(videos.orgId, organizations.id)) + .where( + and( + eq(spaceVideos.spaceId, access.spaceId), + isNull(spaceVideos.folderId), + isNull(organizations.tombstoneAt), + ), + ) + .limit(MAX_SELECT_ALL_ITEMS); + return rows.map((row) => row.id); + } + + const access = await getOrganizationAccess( + user.id, + view.organizationId as Organisation.OrganisationId, + ); + if (!access || !canManageOrganizationMembers(access.role)) + throw new Error("Forbidden"); + const rows = await db() + .selectDistinct({ id: videos.id }) + .from(sharedVideos) + .innerJoin(videos, eq(sharedVideos.videoId, videos.id)) + .where( + and( + eq(sharedVideos.organizationId, access.id), + isNull(sharedVideos.folderId), + ), + ) + .limit(MAX_SELECT_ALL_ITEMS); + return rows.map((row) => row.id); +} diff --git a/apps/web/actions/caps/page-size.ts b/apps/web/actions/caps/page-size.ts new file mode 100644 index 00000000000..6039423b727 --- /dev/null +++ b/apps/web/actions/caps/page-size.ts @@ -0,0 +1,27 @@ +"use server"; + +import { db } from "@cap/database"; +import { getCurrentUser } from "@cap/database/auth/session"; +import { users } from "@cap/database/schema"; +import { eq, sql } from "drizzle-orm"; +import { isDashboardPageSize } from "@/lib/dashboard-page-size"; +import { userPreferencesObject } from "@/lib/user-preferences-sql"; + +export async function setDashboardPageSize(pageSize: unknown) { + if (!isDashboardPageSize(pageSize)) throw new Error("Unsupported page size"); + const user = await getCurrentUser(); + if (!user) throw new Error("Unauthorized"); + + // JSON_SET will not create a missing parent object, so the `dashboard` key + // is merged as a whole object onto the normalised preferences. + await db() + .update(users) + .set({ + preferences: sql`JSON_MERGE_PATCH(${userPreferencesObject()}, CAST(${JSON.stringify( + { dashboard: { pageSize } }, + )} AS JSON))`, + }) + .where(eq(users.id, user.id)); + + return { pageSize }; +} diff --git a/apps/web/actions/videos/archive.ts b/apps/web/actions/videos/archive.ts new file mode 100644 index 00000000000..e7b8ea185c1 --- /dev/null +++ b/apps/web/actions/videos/archive.ts @@ -0,0 +1,52 @@ +"use server"; + +import { db } from "@cap/database"; +import { getCurrentUser } from "@cap/database/auth/session"; +import { videos } from "@cap/database/schema"; +import type { Video } from "@cap/web-domain"; +import { and, eq, inArray, isNotNull, isNull, sql } from "drizzle-orm"; +import { revalidatePath } from "next/cache"; +import { MAX_ARCHIVE_ITEMS } from "@/lib/video-archive"; + +function affectedRows(result: unknown) { + const header = Array.isArray(result) ? result[0] : result; + return (header as { affectedRows?: number } | undefined)?.affectedRows ?? 0; +} + +// Archiving only hides a Cap from its owner's library. The share link, space +// and organization sharing, comments and files all stay exactly as they were, +// so only the owner may do it and nothing else is touched. +export async function setVideosArchived(input: { + videoIds: Video.VideoId[]; + archived: boolean; +}) { + const user = await getCurrentUser(); + if (!user) throw new Error("Unauthorized"); + + const videoIds = Array.isArray(input.videoIds) + ? [...new Set(input.videoIds.filter((id) => typeof id === "string"))] + : []; + if (videoIds.length === 0) return { updated: 0 }; + if (videoIds.length > MAX_ARCHIVE_ITEMS) + throw new Error(`You can archive up to ${MAX_ARCHIVE_ITEMS} Caps at once`); + const archived = input.archived === true; + + const result = await db() + .update(videos) + .set({ + archivedAt: archived ? new Date() : null, + updatedAt: sql`${videos.updatedAt}`, + }) + .where( + and( + eq(videos.ownerId, user.id), + inArray(videos.id, videoIds), + archived ? isNull(videos.archivedAt) : isNotNull(videos.archivedAt), + ), + ); + + revalidatePath("/dashboard/caps"); + revalidatePath("/dashboard/caps/archived"); + revalidatePath("/dashboard/folder/[id]", "page"); + return { updated: affectedRows(result) }; +} diff --git a/apps/web/app/(org)/dashboard/_components/dashboard-titles.ts b/apps/web/app/(org)/dashboard/_components/dashboard-titles.ts index 28d317bb257..77857a75ad0 100644 --- a/apps/web/app/(org)/dashboard/_components/dashboard-titles.ts +++ b/apps/web/app/(org)/dashboard/_components/dashboard-titles.ts @@ -2,6 +2,10 @@ export type DashboardCrumb = { label: string; href?: string }; const exact: Record = { "/dashboard/caps": [{ label: "My Caps" }], + "/dashboard/caps/archived": [ + { label: "My Caps", href: "/dashboard/caps" }, + { label: "Archived" }, + ], "/dashboard/caps/record": [{ label: "Record a Cap" }], "/dashboard/analytics": [{ label: "Analytics" }], "/dashboard/import": [{ label: "Import Media" }], diff --git a/apps/web/app/(org)/dashboard/caps/Caps.tsx b/apps/web/app/(org)/dashboard/caps/Caps.tsx index c9c232cdc4c..38202fd2e5c 100644 --- a/apps/web/app/(org)/dashboard/caps/Caps.tsx +++ b/apps/web/app/(org)/dashboard/caps/Caps.tsx @@ -4,14 +4,19 @@ import type { videos as videosSchema } from "@cap/database/schema"; import type { VideoMetadata } from "@cap/database/types"; import type { SpaceRuleSource, ViewerSettingKey } from "@cap/web-backend"; import type { ImageUpload, Video } from "@cap/web-domain"; +import { faBoxArchive } from "@fortawesome/free-solid-svg-icons/faBoxArchive"; +import clsx from "clsx"; import { Effect, Exit } from "effect"; +import Link from "next/link"; import { useRouter, useSearchParams } from "next/navigation"; -import { useEffect, useMemo, useRef, useState } from "react"; +import { useEffect, useMemo, useState } from "react"; import { toast } from "sonner"; +import { FontAwesomeIcon } from "@/components/FontAwesomeIcon"; import { type SeededThumbnails, SeededThumbnailsProvider, } from "@/components/VideoThumbnail"; +import { DEFAULT_DASHBOARD_PAGE_SIZE } from "@/lib/dashboard-page-size"; import { useEffectMutation, useRpcClient } from "@/lib/EffectRuntime"; import { parsePageParam } from "@/lib/page-param"; import { useVideosAnalyticsQuery } from "@/lib/Queries/Analytics"; @@ -22,12 +27,19 @@ import { UploadPlaceholderCard, } from "./components"; import { CapCard } from "./components/CapCard/CapCard"; +import { + CapListHeader, + listControlClass, + PageSizeSelect, +} from "./components/CapListHeader"; import { CapPagination } from "./components/CapPagination"; import { DragHint } from "./components/DragHint"; import { EmptyCapState } from "./components/EmptyCapState"; import type { FolderDataType } from "./components/Folder"; import { FoldersSection } from "./components/FoldersSection"; import { QuickActions } from "./components/QuickActions"; +import { useArchiveCaps } from "./components/useArchiveCaps"; +import { useCapSelection } from "./components/useCapSelection"; import { useCapsMoved } from "./components/useCapsMoved"; import { useUploadingStatus } from "./UploadingContext"; @@ -64,6 +76,7 @@ export type VideoData = { inheritedSpaceSettings?: Partial>; hasActiveUpload: boolean; settings?: Partial> | null; + archivedAt?: Date | null; }[]; export const Caps = ({ @@ -72,28 +85,64 @@ export const Caps = ({ analyticsEnabled, folders, thumbnails, + pageSize = DEFAULT_DASHBOARD_PAGE_SIZE, + archivedCount = 0, + view = "library", }: { data: VideoData; count: number; folders: FolderDataType[]; analyticsEnabled: boolean; thumbnails?: SeededThumbnails; + pageSize?: number; + archivedCount?: number; + view?: "library" | "archived"; }) => { const router = useRouter(); const params = useSearchParams(); const page = parsePageParam(params.get("page")); const { user } = useDashboardContext(); - const limit = 15; + const isArchivedView = view === "archived"; const [openNewFolderDialog, setOpenNewFolderDialog] = useState(false); - const totalPages = Math.ceil(count / limit); - const previousCountRef = useRef(0); - const [selectedCaps, setSelectedCaps] = useState([]); + const totalPages = Math.ceil(count / pageSize); const moveLocation = { type: "personal" } as const; + const [isUploading, uploadingCapId] = useUploadingStatus(); + const visibleVideos = useMemo( + () => + !isArchivedView && isUploading && uploadingCapId + ? data.filter((video) => video.id !== uploadingCapId) + : data, + [data, isArchivedView, isUploading, uploadingCapId], + ); + const pageIds = useMemo( + () => visibleVideos.map((video) => video.id), + [visibleVideos], + ); + const selectAllView = useMemo( + () => + isArchivedView + ? ({ type: "archived" } as const) + : ({ type: "personal" } as const), + [isArchivedView], + ); + const selection = useCapSelection({ + pageIds, + totalCount: count, + view: selectAllView, + }); + const selectedCaps = selection.selected; + const setSelectedCaps = selection.setSelected; + useCapsMoved((ids) => setSelectedCaps((current) => current.filter((id) => !ids.includes(id))), ); + const archiveCaps = useArchiveCaps({ + onDone: (ids) => + setSelectedCaps((current) => current.filter((id) => !ids.includes(id))), + }); + const anyCapSelected = selectedCaps.length > 0; const analyticsQuery = useVideosAnalyticsQuery( @@ -104,18 +153,6 @@ export const Caps = ({ analyticsQuery.data || {}; const isLoadingAnalytics = analyticsEnabled && analyticsQuery.isLoading; - const handleCapSelection = (capId: Video.VideoId) => { - setSelectedCaps((prev) => { - const newSelection = prev.includes(capId) - ? prev.filter((id) => id !== capId) - : [...prev, capId]; - - previousCountRef.current = prev.length; - - return newSelection; - }); - }; - const rpc = useRpcClient() as { VideoDelete: (id: Video.VideoId) => Effect.Effect; }; @@ -200,10 +237,6 @@ export const Caps = ({ useEffect(() => { const handleKeyDown = (e: KeyboardEvent) => { - if (e.key === "Escape" && selectedCaps.length > 0) { - setSelectedCaps([]); - } - if ( (e.key === "Delete" || e.key === "Backspace") && selectedCaps.length > 0 @@ -226,17 +259,6 @@ export const Caps = ({ deleteCaps(selectedCaps); } } - - if (e.key === "a" && (e.ctrlKey || e.metaKey) && data.length > 0) { - if ( - !["INPUT", "TEXTAREA", "SELECT"].includes( - document.activeElement?.tagName || "", - ) - ) { - e.preventDefault(); - setSelectedCaps(data.map((cap) => cap.id)); - } - } }; window.addEventListener("keydown", handleKeyDown); @@ -244,45 +266,85 @@ export const Caps = ({ return () => { window.removeEventListener("keydown", handleKeyDown); }; - }, [selectedCaps, data, deleteCaps, isDeletingCaps]); + }, [selectedCaps, deleteCaps, isDeletingCaps]); - const [isUploading, uploadingCapId] = useUploadingStatus(); - const visibleVideos = useMemo( - () => - isUploading && uploadingCapId - ? data.filter((video) => video.id !== uploadingCapId) - : data, - [data, isUploading, uploadingCapId], - ); + if ( + !isArchivedView && + count === 0 && + folders.length === 0 && + archivedCount === 0 + ) + return ; - if (count === 0 && folders.length === 0) return ; + const archivedLink = + !isArchivedView && archivedCount > 0 ? ( + + + Archived + + {archivedCount.toLocaleString("en-US")} + + + ) : null; return (
- - setOpenNewFolderDialog(true)} /> - + {isArchivedView ? ( +
+

+ Archived Caps are hidden from My Caps and your folders. Their links, + comments and any spaces they are shared with keep working. +

+
+ ) : ( + <> + + setOpenNewFolderDialog(true)} /> + + + )} + {isArchivedView && visibleVideos.length === 0 && ( +
+

Nothing archived

+

+ Archive a Cap from its menu to tidy up My Caps without deleting + anything. +

+
+ )} + {visibleVideos.length === 0 && archivedLink && ( +
{archivedLink}
+ )} {visibleVideos.length > 0 && ( <> -
-

- Videos and screenshots -

- {count} -
+ + {archivedLink} + + + } + />
- {isUploading && ( + {!isArchivedView && isUploading && ( )} {visibleVideos.map((video) => { @@ -303,11 +365,20 @@ export const Caps = ({ isLoadingAnalytics={isLoadingAnalytics} isSelected={selectedCaps.includes(video.id)} anyCapSelected={anyCapSelected} - onSelectToggle={() => handleCapSelection(video.id)} + onSelectToggle={(options) => + selection.toggle(video.id, options) + } selectedIds={selectedCaps} - canMove + canMove={!isArchivedView} moveLocation={moveLocation} moveRootLabel="My Caps" + isArchived={isArchivedView} + onArchiveToggle={() => + void archiveCaps.mutate({ + ids: [video.id], + archived: !isArchivedView, + }) + } /> ); })} @@ -315,9 +386,17 @@ export const Caps = ({ )} - {(data.length > limit || data.length === limit || page !== 1) && ( + {(data.length >= pageSize || page !== 1) && (
- + `/dashboard/caps/archived?page=${target}` + : undefined + } + />
)} deleteCaps(selectedCaps)} isDeleting={isDeletingCaps || isDeletingCap} - moveLocation={moveLocation} - moveRootLabel="My Caps" + moveLocation={isArchivedView ? undefined : moveLocation} + moveRootLabel={isArchivedView ? undefined : "My Caps"} + selection={selection} + archive={{ + mode: isArchivedView ? "unarchive" : "archive", + isPending: archiveCaps.isPending, + onArchive: () => + void archiveCaps.mutate({ + ids: selectedCaps, + archived: !isArchivedView, + }), + }} /> - + {!isArchivedView && ( + + )}
); }; diff --git a/apps/web/app/(org)/dashboard/caps/archived/page.tsx b/apps/web/app/(org)/dashboard/caps/archived/page.tsx new file mode 100644 index 00000000000..03b8811641c --- /dev/null +++ b/apps/web/app/(org)/dashboard/caps/archived/page.tsx @@ -0,0 +1,15 @@ +import type { Metadata } from "next"; +import { CapsPageView } from "../caps-page-data"; + +export const metadata: Metadata = { + title: "Archived — Cap", +}; + +export default async function ArchivedCapsPage( + props: PageProps<"/dashboard/caps/archived">, +) { + return CapsPageView({ + searchParams: await props.searchParams, + view: "archived", + }); +} diff --git a/apps/web/app/(org)/dashboard/caps/caps-page-data.tsx b/apps/web/app/(org)/dashboard/caps/caps-page-data.tsx new file mode 100644 index 00000000000..94cd8dfb8c8 --- /dev/null +++ b/apps/web/app/(org)/dashboard/caps/caps-page-data.tsx @@ -0,0 +1,404 @@ +import { db } from "@cap/database"; +import { getCurrentUser } from "@cap/database/auth/session"; +import { + comments, + folders, + organizations, + sharedVideos, + spaces, + spaceVideos, + users, + videos, + videoUploads, +} from "@cap/database/schema"; +import { serverEnv } from "@cap/env"; +import { + Database, + ImageUploads, + resolveEffectiveVideoRules, +} from "@cap/web-backend"; +import { type ImageUpload, Video } from "@cap/web-domain"; +import { + and, + desc, + eq, + inArray, + isNotNull, + isNull, + or, + sql, +} from "drizzle-orm"; +import { type Array, Effect } from "effect"; +import { redirect } from "next/navigation"; +import { resolveDashboardPageSize } from "@/lib/dashboard-page-size"; +import { parsePageParam } from "@/lib/page-param"; +import { seedThumbnailUrls } from "@/lib/seeded-thumbnails"; +import { runPromise } from "@/lib/server"; +import { Caps } from "./Caps"; + +// Helper function to fetch shared spaces data for videos +const getSharedSpacesForVideos = Effect.fn(function* ( + videoIds: Video.VideoId[], +) { + if (videoIds.length === 0) return {}; + + const db = yield* Database; + + const [spaceSharing, orgSharing] = yield* Effect.all( + [ + db.use((db) => + db + .select({ + videoId: spaceVideos.videoId, + id: spaces.id, + name: spaces.name, + organizationId: spaces.organizationId, + iconUrl: spaces.iconUrl, + settings: spaces.settings, + hasPassword: sql`${spaces.password} IS NOT NULL`.mapWith(Boolean), + }) + .from(spaceVideos) + .innerJoin(spaces, eq(spaceVideos.spaceId, spaces.id)) + .innerJoin(organizations, eq(spaces.organizationId, organizations.id)) + .where(inArray(spaceVideos.videoId, videoIds)), + ), + db.use((db) => + db + .select({ + videoId: sharedVideos.videoId, + id: organizations.id, + name: organizations.name, + organizationId: organizations.id, + iconUrl: organizations.iconUrl, + }) + .from(sharedVideos) + .innerJoin( + organizations, + eq(sharedVideos.organizationId, organizations.id), + ) + .where(inArray(sharedVideos.videoId, videoIds)), + ), + ], + { concurrency: "unbounded" }, + ); + + // Combine and group by videoId + const sharedSpacesMap: Record< + string, + Array<{ + id: string; + name: string; + organizationId: string; + isOrg: boolean; + iconUrl?: ImageUpload.ImageUrlOrKey | null; + settings?: (typeof spaces.$inferSelect)["settings"]; + hasPassword: boolean; + }> + > = {}; + + // Add space-level sharing + spaceSharing.forEach((space) => { + if (!sharedSpacesMap[space.videoId]) { + sharedSpacesMap[space.videoId] = []; + } + sharedSpacesMap[space.videoId]?.push({ + id: space.id, + name: space.name, + organizationId: space.organizationId, + isOrg: false, + iconUrl: space.iconUrl, + settings: space.settings, + hasPassword: space.hasPassword, + }); + }); + + // Add organization-level sharing + orgSharing.forEach((org) => { + if (!sharedSpacesMap[org.videoId]) { + sharedSpacesMap[org.videoId] = []; + } + sharedSpacesMap[org.videoId]?.push({ + id: org.id, + name: org.name, + organizationId: org.organizationId, + isOrg: true, + iconUrl: org.iconUrl, + settings: null, + hasPassword: false, + }); + }); + + return sharedSpacesMap; +}); + +export async function CapsPageView({ + searchParams, + view, +}: { + searchParams: Record; + view: "library" | "archived"; +}) { + const user = await getCurrentUser(); + + if (!user || !user.id) { + redirect("/login"); + } + + const page = parsePageParam(searchParams.page); + const limit = resolveDashboardPageSize({ + limitParam: searchParams.limit, + preferences: user.preferences, + }); + const isArchivedView = view === "archived"; + + const userId = user.id; + const offset = (page - 1) * limit; + + // One pass gives both the library count and the archived count, so the + // Archived entry costs no extra round trip. The OR keeps the library rows + // (root, not archived) and every archived row, wherever it is filed. + const totalCountPromise = db() + .select({ + count: + sql`count(case when ${videos.archivedAt} is null then 1 end)`.mapWith( + Number, + ), + archivedCount: + sql`count(case when ${videos.archivedAt} is not null then 1 end)`.mapWith( + Number, + ), + }) + .from(videos) + .leftJoin(organizations, eq(videos.orgId, organizations.id)) + .where( + and( + eq(videos.ownerId, userId), + eq(videos.orgId, user.activeOrganizationId), + eq(organizations.id, user.activeOrganizationId), + or(isNull(videos.folderId), isNotNull(videos.archivedAt)), + isNull(organizations.tombstoneAt), + ), + ); + + const capsPage = db() + .select({ id: videos.id }) + .from(videos) + .leftJoin(organizations, eq(videos.orgId, organizations.id)) + .where( + and( + eq(videos.ownerId, userId), + eq(videos.orgId, user.activeOrganizationId), + isArchivedView + ? isNotNull(videos.archivedAt) + : and(isNull(videos.folderId), isNull(videos.archivedAt)), + isNull(organizations.tombstoneAt), + ), + ) + .orderBy( + ...(isArchivedView + ? [desc(videos.archivedAt), desc(videos.id)] + : [desc(videos.effectiveCreatedAt), desc(videos.id)]), + ) + .limit(limit) + .offset(offset) + .as("caps_page"); + + const videoDataPromise = db() + .select({ + id: videos.id, + ownerId: videos.ownerId, + name: videos.name, + createdAt: videos.createdAt, + metadata: videos.metadata, + source: videos.source, + isScreenshot: videos.isScreenshot, + duration: videos.duration, + public: videos.public, + totalComments: sql`COUNT(DISTINCT CASE WHEN ${comments.type} = 'text' THEN ${comments.id} END)`, + totalReactions: sql`COUNT(DISTINCT CASE WHEN ${comments.type} = 'emoji' THEN ${comments.id} END)`, + sharedOrganizations: sql< + { + id: string; + name: string; + iconUrl: ImageUpload.ImageUrlOrKey | null; + }[] + >` + COALESCE( + JSON_ARRAYAGG( + JSON_OBJECT( + 'id', ${organizations.id}, + 'name', ${organizations.name}, + 'iconUrl', ${organizations.iconUrl} + ) + ), + JSON_ARRAY() + ) + `, + ownerName: users.name, + effectiveDate: videos.effectiveCreatedAt, + hasPassword: sql`${videos.password} IS NOT NULL`.mapWith(Boolean), + hasActiveUpload: + sql`${videoUploads.videoId} IS NOT NULL AND ${videos.isScreenshot} = false`.mapWith( + Boolean, + ), + settings: videos.settings, + archivedAt: videos.archivedAt, + }) + .from(videos) + .innerJoin(capsPage, eq(videos.id, capsPage.id)) + .leftJoin(comments, eq(videos.id, comments.videoId)) + .leftJoin(organizations, eq(videos.orgId, organizations.id)) + .leftJoin(users, eq(videos.ownerId, users.id)) + .leftJoin(videoUploads, eq(videos.id, videoUploads.videoId)) + .groupBy( + videos.id, + videos.ownerId, + videos.name, + videos.createdAt, + videos.metadata, + videos.source, + videos.isScreenshot, + videos.duration, + videos.public, + videos.password, + videos.settings, + videos.orgId, + videos.archivedAt, + users.name, + ) + .orderBy( + ...(isArchivedView + ? [desc(videos.archivedAt), desc(videos.id)] + : [desc(videos.effectiveCreatedAt), desc(videos.id)]), + ); + + const foldersDataPromise = isArchivedView + ? Promise.resolve([]) + : db() + .select({ + id: folders.id, + name: folders.name, + color: folders.color, + public: folders.public, + parentId: folders.parentId, + createdAt: folders.createdAt, + videoCount: sql`( + SELECT COUNT(*) FROM videos WHERE videos.folderId = folders.id AND videos.archivedAt IS NULL + )`, + }) + .from(folders) + .where( + and( + eq(folders.organizationId, user.activeOrganizationId), + eq(folders.createdById, user.id), + isNull(folders.parentId), + isNull(folders.spaceId), + ), + ); + + const organizationSettingsPromise = user.activeOrganizationId + ? db() + .select({ settings: organizations.settings }) + .from(organizations) + .where(eq(organizations.id, user.activeOrganizationId)) + .limit(1) + : Promise.resolve([]); + + const [totalCountResult, videoData, foldersData, [organizationSettingsRow]] = + await Promise.all([ + totalCountPromise, + videoDataPromise, + foldersDataPromise, + organizationSettingsPromise, + ]); + const totalCount = isArchivedView + ? (totalCountResult[0]?.archivedCount ?? 0) + : (totalCountResult[0]?.count ?? 0); + const archivedCount = totalCountResult[0]?.archivedCount ?? 0; + const organizationSettings = organizationSettingsRow?.settings ?? null; + + const videoIds = videoData.map((video) => video.id); + const thumbnails = seedThumbnailUrls( + user, + videoData + .filter((video) => !video.hasActiveUpload) + .map((video) => Video.VideoId.make(video.id)), + ); + const sharedSpacesMap = + await getSharedSpacesForVideos(videoIds).pipe(runPromise); + + const processedVideoData = await Effect.all( + videoData.map( + Effect.fn(function* (video) { + const imageUploads = yield* ImageUploads; + + const { effectiveDate: _effectiveDate, ...videoWithoutEffectiveDate } = + video; + const sharedSpaces = sharedSpacesMap[video.id] ?? []; + const rules = resolveEffectiveVideoRules({ + videoSettings: video.settings, + organizationSettings, + spaces: sharedSpaces.filter((space) => !space.isOrg), + }); + + return { + ...videoWithoutEffectiveDate, + id: Video.VideoId.make(video.id), + foldersData, + settings: video.settings, + hasInheritedPassword: rules.hasInheritedPassword, + inheritedPasswordSources: rules.inheritedPasswordSources, + inheritedSpaceSettings: rules.inheritedSettings, + sharedOrganizations: yield* Effect.all( + (video.sharedOrganizations ?? []) + .filter((organization) => organization.id !== null) + .map( + Effect.fn(function* (org) { + return { + ...org, + iconUrl: org.iconUrl + ? yield* imageUploads.resolveImageUrl(org.iconUrl) + : null, + }; + }), + ), + ), + sharedSpaces: yield* Effect.all( + sharedSpaces.map( + Effect.fn(function* (space) { + return { + ...space, + iconUrl: space.iconUrl + ? yield* imageUploads.resolveImageUrl(space.iconUrl) + : null, + }; + }), + ), + ), + ownerName: video.ownerName ?? "", + metadata: video.metadata as + | { + customCreatedAt?: string; + [key: string]: unknown; + } + | undefined, + }; + }), + ), + ).pipe(runPromise); + + return ( + + ); +} diff --git a/apps/web/app/(org)/dashboard/caps/components/CapCard/CapCard.tsx b/apps/web/app/(org)/dashboard/caps/components/CapCard/CapCard.tsx index 2a802a9c2ff..bf5b7407001 100644 --- a/apps/web/app/(org)/dashboard/caps/components/CapCard/CapCard.tsx +++ b/apps/web/app/(org)/dashboard/caps/components/CapCard/CapCard.tsx @@ -11,6 +11,11 @@ import { import { calculateStrokeDashoffset, getProgressCircleConfig } from "@cap/utils"; import type { SpaceRuleSource, ViewerSettingKey } from "@cap/web-backend"; import type { Folder, ImageUpload, Video } from "@cap/web-domain"; +import { faArrowLeft } from "@fortawesome/free-solid-svg-icons/faArrowLeft"; +import { faArrowRight } from "@fortawesome/free-solid-svg-icons/faArrowRight"; +import { faBackwardStep } from "@fortawesome/free-solid-svg-icons/faBackwardStep"; +import { faBoxArchive } from "@fortawesome/free-solid-svg-icons/faBoxArchive"; +import { faBoxOpen } from "@fortawesome/free-solid-svg-icons/faBoxOpen"; import { faChartSimple } from "@fortawesome/free-solid-svg-icons/faChartSimple"; import { faCheck } from "@fortawesome/free-solid-svg-icons/faCheck"; import { faCopy } from "@fortawesome/free-solid-svg-icons/faCopy"; @@ -131,7 +136,7 @@ export interface CapCardProps extends PropsWithChildren { userId?: string; sharedCapCard?: boolean; isSelected?: boolean; - onSelectToggle?: () => void; + onSelectToggle?: (options?: { shiftKey?: boolean }) => void; selectedIds?: Video.VideoId[]; hideSharedStatus?: boolean; anyCapSelected?: boolean; @@ -142,8 +147,18 @@ export interface CapCardProps extends PropsWithChildren { moveLocation?: MoveLocation; moveRootLabel?: string; currentFolderId?: Folder.FolderId | null; + href?: string; + isArchived?: boolean; + onArchiveToggle?: () => void; + reorder?: CapCardReorderActions; } +export type CapCardReorderActions = { + onMoveToStart?: () => void; + onMoveEarlier?: () => void; + onMoveLater?: () => void; +}; + export const CapCard = ({ cap, analytics, @@ -162,6 +177,10 @@ export const CapCard = ({ moveLocation, moveRootLabel, currentFolderId = null, + href, + isArchived = false, + onArchiveToggle, + reorder, }: CapCardProps) => { const { activeOrganization } = useDashboardContext(); @@ -335,7 +354,7 @@ export const CapCard = ({ e.preventDefault(); e.stopPropagation(); if (onSelectToggle) { - onSelectToggle(); + onSelectToggle({ shiftKey: e.shiftKey }); } }; @@ -558,6 +577,42 @@ export const CapCard = ({

Move

)} + {reorder?.onMoveToStart && ( + { + event.stopPropagation(); + reorder.onMoveToStart?.(); + }} + className="flex gap-2 items-center rounded-lg" + > + +

Move to start

+
+ )} + {reorder?.onMoveEarlier && ( + { + event.stopPropagation(); + reorder.onMoveEarlier?.(); + }} + className="flex gap-2 items-center rounded-lg" + > + +

Move earlier

+
+ )} + {reorder?.onMoveLater && ( + { + event.stopPropagation(); + reorder.onMoveLater?.(); + }} + className="flex gap-2 items-center rounded-lg" + > + +

Move later

+
+ )} {isOwner && ( <> + {onArchiveToggle && ( + { + e.stopPropagation(); + onArchiveToggle(); + }} + className="flex gap-2 items-center rounded-lg" + > + +

+ {isArchived ? "Unarchive" : "Archive"} +

+
+ )} {onDelete && ( { @@ -639,9 +711,11 @@ export const CapCard = ({ {!sharedCapCard && onSelectToggle && ( + ); +} + +export function PageSizeSelect({ pageSize }: { pageSize: number }) { + const router = useRouter(); + const [isPending, startTransition] = useTransition(); + + const choose = (next: number) => { + if (next === pageSize) return; + startTransition(async () => { + try { + await setDashboardPageSize(next); + } catch { + toast.error("Couldn't save your page size. Please try again."); + return; + } + const url = new URL(window.location.href); + url.searchParams.delete("page"); + url.searchParams.delete("limit"); + router.replace(`${url.pathname}${url.search}`, { + scroll: false, + }); + router.refresh(); + }); + }; + + return ( + + + + + + {DASHBOARD_PAGE_SIZES.map((size) => ( + choose(size)} + className={clsx( + "gap-2 rounded-lg tabular-nums", + size === pageSize && "text-gray-12", + )} + > + {size} per page + {size === pageSize && ( + + )} + + ))} + + + ); +} + +export function CapListHeader({ + title, + count, + selectionState, + onToggleSelectAll, + actions, +}: { + title: string; + count?: number; + selectionState?: PageSelectionState; + onToggleSelectAll?: () => void; + actions?: ReactNode; +}) { + return ( +
+
+ {selectionState && onToggleSelectAll && ( + + )} +

+ {title} +

+ {typeof count === "number" && ( + + {count.toLocaleString("en-US")} + + )} +
+ {actions &&
{actions}
} +
+ ); +} diff --git a/apps/web/app/(org)/dashboard/caps/components/MoveItemsDialog.tsx b/apps/web/app/(org)/dashboard/caps/components/MoveItemsDialog.tsx index 0fa990b7f89..99445b0eec4 100644 --- a/apps/web/app/(org)/dashboard/caps/components/MoveItemsDialog.tsx +++ b/apps/web/app/(org)/dashboard/caps/components/MoveItemsDialog.tsx @@ -45,11 +45,13 @@ import { useCurrentUser } from "@/app/Layout/AuthContext"; import { useEffectMutation, useRpcClient } from "@/lib/EffectRuntime"; import { buildMoveFolderDestinationRows, + MAX_MOVE_ITEMS, type MoveDestinationGroup, type MoveLocation, moveLocationFolderSpaceId, moveLocationKey, } from "@/lib/move-items"; +import { chunkIds } from "@/lib/video-archive"; type MoveItem = | { @@ -181,14 +183,17 @@ export function MoveItemsDialog({ mutationFn: async () => { if (item.type === "videos") { if (!selectedGroup) throw new Error("Select a destination"); - const placement = { - videoIds: item.videoIds, - folderId: selectedFolderId, - location: selectedGroup.location, - }; - await (ownedVideos - ? placeOwnedVideos({ ...placement, organizationId }) - : moveVideos(placement)); + // "Select all" can hold more Caps than one request accepts. + for (const videoIds of chunkIds(item.videoIds, MAX_MOVE_ITEMS)) { + const placement = { + videoIds, + folderId: selectedFolderId, + location: selectedGroup.location, + }; + await (ownedVideos + ? placeOwnedVideos({ ...placement, organizationId }) + : moveVideos(placement)); + } return; } diff --git a/apps/web/app/(org)/dashboard/caps/components/SelectedCapsBar.tsx b/apps/web/app/(org)/dashboard/caps/components/SelectedCapsBar.tsx index 6e1c17f057a..3dd69b6887c 100644 --- a/apps/web/app/(org)/dashboard/caps/components/SelectedCapsBar.tsx +++ b/apps/web/app/(org)/dashboard/caps/components/SelectedCapsBar.tsx @@ -2,6 +2,8 @@ import { Button } from "@cap/ui"; import type { Folder, Video } from "@cap/web-domain"; +import { faBoxArchive } from "@fortawesome/free-solid-svg-icons/faBoxArchive"; +import { faBoxOpen } from "@fortawesome/free-solid-svg-icons/faBoxOpen"; import { faFilm } from "@fortawesome/free-solid-svg-icons/faFilm"; import { faTrash } from "@fortawesome/free-solid-svg-icons/faTrash"; import NumberFlow from "@number-flow/react"; @@ -12,6 +14,7 @@ import { ConfirmationDialog } from "@/app/(org)/dashboard/_components/Confirmati import { FontAwesomeIcon } from "@/components/FontAwesomeIcon"; import type { MoveLocation } from "@/lib/move-items"; import { MoveItemsDialog } from "./MoveItemsDialog"; +import type { CapSelection } from "./useCapSelection"; interface SelectedCapsBarProps { selectedCaps: Video.VideoId[]; @@ -21,6 +24,19 @@ interface SelectedCapsBarProps { moveLocation?: MoveLocation; moveRootLabel?: string; currentFolderId?: Folder.FolderId | null; + selection?: Pick< + CapSelection, + | "canSelectAllMatching" + | "isAllMatching" + | "isSelectingAll" + | "selectAllMatching" + | "totalCount" + >; + archive?: { + mode: "archive" | "unarchive"; + onArchive: () => void; + isPending?: boolean; + }; } export const SelectedCapsBar = ({ @@ -31,6 +47,8 @@ export const SelectedCapsBar = ({ moveLocation, moveRootLabel, currentFolderId = null, + selection, + archive, }: SelectedCapsBarProps) => { const [confirmOpen, setConfirmOpen] = useState(false); const [moveOpen, setMoveOpen] = useState(false); @@ -45,7 +63,7 @@ export const SelectedCapsBar = ({ {selectedCaps.length > 0 && ( <>
-
+ selected -
- {moveLocation && moveRootLabel && ( -

- Drag them onto a folder, or use Move + + {selection?.canSelectAllMatching && !selection.isAllMatching ? ( + + ) : selection?.isAllMatching ? ( +

+ Every Cap here is selected

+ ) : ( + moveLocation && + moveRootLabel && ( +

+ Drag them onto a folder, or use Move +

+ ) )}
@@ -89,6 +128,23 @@ export const SelectedCapsBar = ({ Move )} + {archive && ( + + )} + + +

+ Sets the order for everyone in this space +

+ {SPACE_VIDEO_ORDER_OPTIONS.map((option) => ( + choose(option.value)} + className={clsx( + "gap-2 rounded-lg", + option.value === order && "text-gray-12", + )} + > + + {option.label} + {option.value === order && ( + + )} + + ))} +
+ + ); +} diff --git a/apps/web/app/(org)/dashboard/spaces/[spaceId]/page.tsx b/apps/web/app/(org)/dashboard/spaces/[spaceId]/page.tsx index 05872687a21..e25d961e14c 100644 --- a/apps/web/app/(org)/dashboard/spaces/[spaceId]/page.tsx +++ b/apps/web/app/(org)/dashboard/spaces/[spaceId]/page.tsx @@ -28,13 +28,22 @@ import { type User, Video, } from "@cap/web-domain"; -import { and, desc, eq, inArray, isNull, or, sql } from "drizzle-orm"; +import { and, desc, eq, inArray, isNull, or, type SQL, sql } from "drizzle-orm"; import { Effect } from "effect"; import type { Metadata } from "next"; import { notFound } from "next/navigation"; +import { resolveDashboardPageSize } from "@/lib/dashboard-page-size"; import { parsePageParam } from "@/lib/page-param"; import { seedThumbnailUrls } from "@/lib/seeded-thumbnails"; import { runPromise } from "@/lib/server"; +import { + type SpaceVideoOrder, + spaceVideoOrderFromSettings, +} from "@/lib/space-video-order"; +import { + spaceVideoOrderBy, + spaceVideoPositionSql, +} from "@/lib/space-video-order-query"; import { SharedCaps } from "./SharedCaps"; export const metadata: Metadata = { @@ -290,9 +299,12 @@ export default async function SharedCapsPage(props: { const searchParams = await props.searchParams; const params = await props.params; const page = parsePageParam(searchParams.page); - const limit = parsePageParam(searchParams.limit, 15); const user = await getCurrentUser(); if (!user) notFound(); + const limit = resolveDashboardPageSize({ + limitParam: searchParams.limit, + preferences: user.preferences, + }); const spaceOrOrg = await Effect.flatMap(Spaces, (s) => s.getSpaceOrOrg(Space.SpaceId.make(params.spaceId)), @@ -306,32 +318,71 @@ export default async function SharedCapsPage(props: { if (spaceOrOrg.variant === "space") { const { space } = spaceOrOrg; + const videoOrder = spaceVideoOrderFromSettings(space.settings); async function fetchSpaceVideos( spaceId: Space.SpaceIdOrOrganisationId, page: number, limit: number, + order: SpaceVideoOrder, ) { const offset = (page - 1) * limit; - const spaceVideosPage = db() - .selectDistinct({ - id: videos.id, - effectiveCreatedAt: videos.effectiveCreatedAt, - }) - .from(spaceVideos) - .innerJoin(videos, eq(spaceVideos.videoId, videos.id)) - .leftJoin(organizations, eq(videos.orgId, organizations.id)) - .where( - and( - eq(spaceVideos.spaceId, spaceId), - isNull(spaceVideos.folderId), - isNull(organizations.tombstoneAt), - ), - ) - .orderBy(desc(videos.effectiveCreatedAt), desc(videos.id)) - .limit(limit) - .offset(offset) - .as("space_videos_page"); + const rootFilter = and( + eq(spaceVideos.spaceId, spaceId), + isNull(spaceVideos.folderId), + isNull(organizations.tombstoneAt), + ); + // Custom order groups by video so a video added to the space twice + // still appears once, at its lowest stored position. + const spaceVideosPage = + order === "custom" + ? db() + .select({ + id: videos.id, + effectiveCreatedAt: videos.effectiveCreatedAt, + position: spaceVideoPositionSql.as("position"), + }) + .from(spaceVideos) + .innerJoin(videos, eq(spaceVideos.videoId, videos.id)) + .leftJoin(organizations, eq(videos.orgId, organizations.id)) + .where(rootFilter) + .groupBy(videos.id, videos.effectiveCreatedAt) + .orderBy( + ...spaceVideoOrderBy(order, { + position: spaceVideoPositionSql, + effectiveCreatedAt: videos.effectiveCreatedAt, + id: videos.id, + }), + ) + .limit(limit) + .offset(offset) + .as("space_videos_page") + : db() + .selectDistinct({ + id: videos.id, + effectiveCreatedAt: videos.effectiveCreatedAt, + position: sql`NULL`.as("position"), + }) + .from(spaceVideos) + .innerJoin(videos, eq(spaceVideos.videoId, videos.id)) + .leftJoin(organizations, eq(videos.orgId, organizations.id)) + .where(rootFilter) + .orderBy( + ...spaceVideoOrderBy(order, { + position: sql`NULL`, + effectiveCreatedAt: videos.effectiveCreatedAt, + id: videos.id, + }), + ) + .limit(limit) + .offset(offset) + .as("space_videos_page"); + const pagePosition = sql.raw("`space_videos_page`.`position`"); + const pageOrder: SQL[] = spaceVideoOrderBy(order, { + position: pagePosition, + effectiveCreatedAt: videos.effectiveCreatedAt, + id: videos.id, + }); const [videoRows, totalCountResult] = await Promise.all([ db() @@ -372,8 +423,9 @@ export default async function SharedCapsPage(props: { videos.settings, videos.password, users.name, + pagePosition, ) - .orderBy(desc(videos.effectiveCreatedAt), desc(videos.id)), + .orderBy(...pageOrder), db() .select({ count: sql`COUNT(DISTINCT ${videos.id})`.mapWith(Number), @@ -405,7 +457,7 @@ export default async function SharedCapsPage(props: { fetchSpaceMembers(space.id).pipe(runPromise), fetchOrganizationMembers(space.organizationId).pipe(runPromise), fetchFolders(space.id, false), - fetchSpaceVideos(space.id, page, limit), + fetchSpaceVideos(space.id, page, limit, videoOrder), fetchOrganizationSettings(space.organizationId), ]); const thumbnails = seedThumbnailUrls( @@ -466,6 +518,8 @@ export default async function SharedCapsPage(props: { currentUserId={user.id} folders={foldersData} thumbnails={thumbnails} + pageSize={limit} + videoOrder={videoOrder} /> ); } @@ -617,6 +671,7 @@ export default async function SharedCapsPage(props: { currentUserId={user.id} folders={foldersData} thumbnails={thumbnails} + pageSize={limit} /> ); } diff --git a/apps/web/lib/space-video-order-query.ts b/apps/web/lib/space-video-order-query.ts new file mode 100644 index 00000000000..64ee102b41b --- /dev/null +++ b/apps/web/lib/space-video-order-query.ts @@ -0,0 +1,66 @@ +import { db } from "@cap/database"; +import { organizations, spaceVideos, videos } from "@cap/database/schema"; +import type { Space } from "@cap/web-domain"; +import { and, asc, desc, eq, isNull, type SQL, sql } from "drizzle-orm"; +import type { SpaceVideoOrder } from "./space-video-order"; + +export const spaceVideoPositionSql = sql< + number | null +>`MIN(${spaceVideos.position})`; + +// Unplaced videos (position NULL) sort first, newest first, so anything added +// after a custom order was set shows up at the top instead of hiding on the +// last page. MySQL sorts NULL before numbers in ascending order. +export function spaceVideoOrderBy( + order: SpaceVideoOrder, + columns: { + position: SQL | SQL.Aliased; + effectiveCreatedAt: typeof videos.effectiveCreatedAt; + id: typeof videos.id; + }, +): SQL[] { + if (order === "oldest") + return [asc(columns.effectiveCreatedAt), asc(columns.id)]; + if (order === "custom") + return [ + asc(columns.position as SQL), + desc(columns.effectiveCreatedAt), + desc(columns.id), + ]; + return [desc(columns.effectiveCreatedAt), desc(columns.id)]; +} + +export async function getSpaceRootVideoOrder( + spaceId: Space.SpaceIdOrOrganisationId, + order: SpaceVideoOrder, + options: { includeScreenshots?: boolean } = {}, +) { + const rows = await db() + .select({ + id: videos.id, + isScreenshot: videos.isScreenshot, + position: spaceVideoPositionSql, + }) + .from(spaceVideos) + .innerJoin(videos, eq(spaceVideos.videoId, videos.id)) + .leftJoin(organizations, eq(videos.orgId, organizations.id)) + .where( + and( + eq(spaceVideos.spaceId, spaceId), + isNull(spaceVideos.folderId), + isNull(organizations.tombstoneAt), + ), + ) + .groupBy(videos.id, videos.isScreenshot, videos.effectiveCreatedAt) + .orderBy( + ...spaceVideoOrderBy(order, { + position: spaceVideoPositionSql, + effectiveCreatedAt: videos.effectiveCreatedAt, + id: videos.id, + }), + ); + + return options.includeScreenshots === false + ? rows.filter((row) => !row.isScreenshot) + : rows; +} diff --git a/apps/web/lib/space-video-order.ts b/apps/web/lib/space-video-order.ts new file mode 100644 index 00000000000..4b9353cb376 --- /dev/null +++ b/apps/web/lib/space-video-order.ts @@ -0,0 +1,93 @@ +export type SpaceVideoOrder = "newest" | "oldest" | "custom"; + +export const SPACE_VIDEO_ORDER_OPTIONS: ReadonlyArray<{ + value: SpaceVideoOrder; + label: string; +}> = [ + { value: "newest", label: "Newest first" }, + { value: "oldest", label: "Oldest first" }, + { value: "custom", label: "Custom order" }, +]; + +export const DEFAULT_SPACE_VIDEO_ORDER: SpaceVideoOrder = "newest"; + +export const MAX_REORDER_ITEMS = 500; + +export function isSpaceVideoOrder(value: unknown): value is SpaceVideoOrder { + return value === "newest" || value === "oldest" || value === "custom"; +} + +export function spaceVideoOrderFromSettings( + settings: { videoOrder?: unknown } | null | undefined, +): SpaceVideoOrder { + return isSpaceVideoOrder(settings?.videoOrder) + ? settings.videoOrder + : DEFAULT_SPACE_VIDEO_ORDER; +} + +export type ReorderPlacement = + | { type: "before"; targetId: string } + | { type: "after"; targetId: string } + | { type: "start" } + | { type: "end" } + | { type: "earlier" } + | { type: "later" }; + +// Moves `movedIds` as one block, keeping their current relative order, to the +// placement. Ids that are not in the list are ignored; a target that is itself +// being moved resolves to the block's current slot. +export function reorderIds( + orderedIds: readonly string[], + movedIds: readonly string[], + placement: ReorderPlacement, +): string[] { + const moving = new Set(movedIds.filter((id) => orderedIds.includes(id))); + if (moving.size === 0) return [...orderedIds]; + + const block = orderedIds.filter((id) => moving.has(id)); + const rest = orderedIds.filter((id) => !moving.has(id)); + + const firstMoved = orderedIds.findIndex((id) => moving.has(id)); + const blockStart = orderedIds + .slice(0, firstMoved) + .filter((id) => !moving.has(id)).length; + + let insertAt: number; + if (placement.type === "earlier") insertAt = Math.max(0, blockStart - 1); + else if (placement.type === "later") + insertAt = Math.min(rest.length, blockStart + 1); + else if (placement.type === "start") insertAt = 0; + else if (placement.type === "end") insertAt = rest.length; + else if (moving.has(placement.targetId)) insertAt = blockStart; + else { + const targetIndex = rest.indexOf(placement.targetId); + if (targetIndex === -1) return [...orderedIds]; + insertAt = placement.type === "before" ? targetIndex : targetIndex + 1; + } + + return [...rest.slice(0, insertAt), ...block, ...rest.slice(insertAt)]; +} + +// Positions are dense (0..n-1) in the new order. Only rows whose stored value +// differs are returned, so a move near the top of a large space rewrites a +// short range instead of the whole list. +export function positionChanges( + current: ReadonlyArray<{ id: string; position: number | null }>, + nextOrder: readonly string[], +): Array<{ id: string; position: number }> { + const stored = new Map(current.map((row) => [row.id, row.position])); + const changes: Array<{ id: string; position: number }> = []; + nextOrder.forEach((id, position) => { + if (stored.get(id) !== position) changes.push({ id, position }); + }); + return changes; +} + +export function nextInOrder( + orderedIds: readonly string[], + currentId: string, +): string | null { + const index = orderedIds.indexOf(currentId); + if (index === -1) return null; + return orderedIds[index + 1] ?? null; +} From 162c92d4b8556b5a75cfd947d20ef37725f11113 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:35:03 +0000 Subject: [PATCH 04/16] feat(web): play the next video when watching from a Space --- .../[videoId]/_components/EmbedVideo.tsx | 2 +- apps/web/app/embed/[videoId]/page.tsx | 2 +- apps/web/app/s/[videoId]/Share.tsx | 4 + .../s/[videoId]/_components/ShareVideo.tsx | 16 ++ .../s/[videoId]/_components/UpNextOverlay.tsx | 240 ++++++++++++++++++ .../[videoId]/_components/up-next-playback.ts | 79 ++++++ apps/web/app/s/[videoId]/page.tsx | 19 +- apps/web/app/s/[videoId]/types.ts | 5 +- apps/web/lib/space-up-next.ts | 69 +++++ 9 files changed, 432 insertions(+), 4 deletions(-) create mode 100644 apps/web/app/s/[videoId]/_components/UpNextOverlay.tsx create mode 100644 apps/web/app/s/[videoId]/_components/up-next-playback.ts create mode 100644 apps/web/lib/space-up-next.ts diff --git a/apps/web/app/embed/[videoId]/_components/EmbedVideo.tsx b/apps/web/app/embed/[videoId]/_components/EmbedVideo.tsx index 889726b9d4d..141efcb0ec8 100644 --- a/apps/web/app/embed/[videoId]/_components/EmbedVideo.tsx +++ b/apps/web/app/embed/[videoId]/_components/EmbedVideo.tsx @@ -56,7 +56,7 @@ type CommentWithAuthor = typeof commentsSchema.$inferSelect & { export const EmbedVideo = forwardRef< HTMLVideoElement, { - data: Omit & { + data: Omit & { hasActiveUpload: boolean | undefined; }; branding: SharePageBranding | null; diff --git a/apps/web/app/embed/[videoId]/page.tsx b/apps/web/app/embed/[videoId]/page.tsx index 0245978513a..5606109a9d9 100644 --- a/apps/web/app/embed/[videoId]/page.tsx +++ b/apps/web/app/embed/[videoId]/page.tsx @@ -214,7 +214,7 @@ async function EmbedContent({ startTime, minimal, }: { - video: Omit & { + video: Omit & { sharedOrganization: { organizationId: Organisation.OrganisationId } | null; hasActiveUpload: boolean | undefined; orgSettings?: (typeof organizations.$inferSelect)["settings"] | null; diff --git a/apps/web/app/s/[videoId]/Share.tsx b/apps/web/app/s/[videoId]/Share.tsx index bc1ffaeb827..a38918cb566 100644 --- a/apps/web/app/s/[videoId]/Share.tsx +++ b/apps/web/app/s/[videoId]/Share.tsx @@ -24,6 +24,7 @@ import { import type { OrganizationSettings } from "@/app/(org)/dashboard/dashboard-data"; import { SignedImageUrl } from "@/components/SignedImageUrl"; import type { ShareDashboardDestination } from "@/lib/share-dashboard-destination"; +import type { SpaceUpNext } from "@/lib/space-up-next"; import { VideoStatusNotFoundError, videoStatusQueryOptions, @@ -186,6 +187,7 @@ type TranscriptionStatus = interface ShareProps { data: VideoData; + upNext?: SpaceUpNext | null; initialPlaybackUrl?: Promise; serverPlaybackUrl?: string | null; comments: MaybePromise; @@ -342,6 +344,7 @@ export const Share = ({ viewerSignedIn = false, header, dashboardDestination = null, + upNext = null, }: ShareProps) => { const isScreenshot = data.isScreenshot === true; // Memoized: a fresh Date each render would defeat the memoized `data` @@ -1007,6 +1010,7 @@ export const Share = ({ defaultPlaybackSpeed={defaultPlaybackSpeed} viewerIsOwner={viewerId === data.owner.id} callToAction={data.callToAction} + upNext={upNext} ref={playerRef} /> )} diff --git a/apps/web/app/s/[videoId]/_components/ShareVideo.tsx b/apps/web/app/s/[videoId]/_components/ShareVideo.tsx index 3fa1d947380..61bfe270c23 100644 --- a/apps/web/app/s/[videoId]/_components/ShareVideo.tsx +++ b/apps/web/app/s/[videoId]/_components/ShareVideo.tsx @@ -21,12 +21,14 @@ import { import { finalizeDesktopSegmentsRecording } from "@/actions/video/finalize-desktop-segments"; import { Tooltip } from "@/components/Tooltip"; import type { ShareCallToAction } from "@/lib/share-call-to-action"; +import type { SpaceUpNext } from "@/lib/space-up-next"; import type { VideoData } from "../types"; import { type CaptionLanguage, useCaptionContext } from "./CaptionContext"; import { PreparingVideoOverlay, RecordingInProgressOverlay, } from "./RecordingInProgress"; +import { useContinueFromUpNext } from "./up-next-playback"; import { isRecordingUpload, shouldDeferPlaybackSource, @@ -65,6 +67,10 @@ const UploadProgressTracker = dynamic(() => import("./UploadProgressTracker"), { const importUpgradeModal = () => import("@/components/UpgradeModal").then((m) => m.UpgradeModal); const UpgradeModal = dynamic(importUpgradeModal, { ssr: false }); +const UpNextOverlay = dynamic( + () => import("./UpNextOverlay").then((m) => m.UpNextOverlay), + { ssr: false }, +); type AiGenerationStatus = | "QUEUED" @@ -106,6 +112,7 @@ export const ShareVideo = forwardRef< defaultPlaybackSpeed?: number; viewerIsOwner?: boolean; callToAction?: ShareCallToAction | null; + upNext?: SpaceUpNext | null; } >( ( @@ -131,11 +138,13 @@ export const ShareVideo = forwardRef< defaultPlaybackSpeed, viewerIsOwner = false, callToAction = null, + upNext = null, }, ref, ) => { const videoRef = useRef(null); useImperativeHandle(ref, () => videoRef.current as HTMLVideoElement, []); + useContinueFromUpNext(videoRef, data.id); const router = useRouter(); const handleUploadComplete = useCallback(() => { router.refresh(); @@ -631,6 +640,13 @@ export const ShareVideo = forwardRef< callToAction={callToAction} /> )} + {upNext && !isActivelyRecording && ( + + )} {showFinalizeRecordingControl && (
diff --git a/apps/web/app/s/[videoId]/_components/UpNextOverlay.tsx b/apps/web/app/s/[videoId]/_components/UpNextOverlay.tsx new file mode 100644 index 00000000000..6e204a2321e --- /dev/null +++ b/apps/web/app/s/[videoId]/_components/UpNextOverlay.tsx @@ -0,0 +1,240 @@ +"use client"; + +import { AnimatePresence, motion, useReducedMotion } from "motion/react"; +import Image from "next/image"; +import { useRouter } from "next/navigation"; +import { + type RefObject, + useCallback, + useEffect, + useRef, + useState, +} from "react"; +import type { SpaceUpNext } from "@/lib/space-up-next"; +import { markUpNextContinue, whenVideoMounted } from "./up-next-playback"; + +export const UP_NEXT_COUNTDOWN_SECONDS = 8; +const AUTOPLAY_STORAGE_KEY = "cap:space-autoplay"; +const RING_RADIUS = 15; +const RING_CIRCUMFERENCE = 2 * Math.PI * RING_RADIUS; + +function readAutoplay() { + try { + return window.localStorage.getItem(AUTOPLAY_STORAGE_KEY) !== "off"; + } catch { + return true; + } +} + +function writeAutoplay(enabled: boolean) { + try { + window.localStorage.setItem(AUTOPLAY_STORAGE_KEY, enabled ? "on" : "off"); + } catch {} +} + +function formatDuration(seconds: number | null) { + if (!seconds || !Number.isFinite(seconds) || seconds <= 0) return null; + const total = Math.round(seconds); + const minutes = Math.floor(total / 60); + return `${minutes}:${String(total % 60).padStart(2, "0")}`; +} + +export function upNextHref(upNext: SpaceUpNext) { + return `/s/${upNext.video.id}?space=${encodeURIComponent(upNext.spaceId)}`; +} + +export function UpNextOverlay({ + upNext, + videoRef, + holdAutoplay = false, +}: { + upNext: SpaceUpNext; + videoRef: RefObject; + holdAutoplay?: boolean; +}) { + const router = useRouter(); + const reduceMotion = useReducedMotion(); + const [ended, setEnded] = useState(false); + const [autoplay, setAutoplay] = useState(true); + const [cancelled, setCancelled] = useState(false); + const [remaining, setRemaining] = useState(UP_NEXT_COUNTDOWN_SECONDS); + const navigatedRef = useRef(false); + const href = upNextHref(upNext); + + useEffect(() => { + setAutoplay(readAutoplay()); + }, []); + + useEffect(() => { + const onEnded = () => { + setEnded(true); + setCancelled(false); + setRemaining(UP_NEXT_COUNTDOWN_SECONDS); + }; + const onResume = () => setEnded(false); + return whenVideoMounted(videoRef, (video) => { + video.addEventListener("ended", onEnded); + video.addEventListener("play", onResume); + video.addEventListener("seeking", onResume); + return () => { + video.removeEventListener("ended", onEnded); + video.removeEventListener("play", onResume); + video.removeEventListener("seeking", onResume); + }; + }); + }, [videoRef]); + + const playNext = useCallback(() => { + if (navigatedRef.current) return; + navigatedRef.current = true; + markUpNextContinue(upNext.video.id); + router.push(href); + }, [href, router, upNext.video.id]); + + useEffect(() => { + router.prefetch(href); + }, [href, router]); + + const counting = ended && autoplay && !cancelled && !holdAutoplay; + + useEffect(() => { + if (!counting) return; + if (remaining <= 0) { + playNext(); + return; + } + const timer = window.setTimeout(() => setRemaining((r) => r - 1), 1000); + return () => window.clearTimeout(timer); + }, [counting, remaining, playNext]); + + const toggleAutoplay = () => { + setAutoplay((current) => { + writeAutoplay(!current); + return !current; + }); + setRemaining(UP_NEXT_COUNTDOWN_SECONDS); + }; + + const duration = formatDuration(upNext.video.duration); + const progress = counting ? remaining / UP_NEXT_COUNTDOWN_SECONDS : 1; + + return ( + + {ended && ( + +
+ +
+

+ {counting ? `Up next in ${remaining}` : "Up next"} +

+

+ {upNext.video.name} +

+

+ {duration ? `${duration} · ` : ""} + {upNext.spaceName} +

+
+
+
+ +
+ {counting && ( + + )} + +
+
+
+ )} +
+ ); +} diff --git a/apps/web/app/s/[videoId]/_components/up-next-playback.ts b/apps/web/app/s/[videoId]/_components/up-next-playback.ts new file mode 100644 index 00000000000..07cdee8b961 --- /dev/null +++ b/apps/web/app/s/[videoId]/_components/up-next-playback.ts @@ -0,0 +1,79 @@ +"use client"; + +import { type RefObject, useEffect } from "react"; + +const CONTINUE_STORAGE_KEY = "cap:up-next-continue"; +const VIDEO_POLL_MS = 200; +const VIDEO_POLL_LIMIT = 150; +export function markUpNextContinue(videoId: string) { + try { + window.sessionStorage.setItem(CONTINUE_STORAGE_KEY, videoId); + } catch {} +} + +// The player mounts after the page (and not at all while a video is still +// processing), so the element is looked up on a short, bounded poll. +export function whenVideoMounted( + videoRef: RefObject, + onMounted: (video: HTMLVideoElement) => () => void, +) { + let cleanup: (() => void) | null = null; + let tries = 0; + const check = () => { + const video = videoRef.current; + if (video) { + window.clearInterval(timer); + cleanup = onMounted(video); + } else if (++tries >= VIDEO_POLL_LIMIT) window.clearInterval(timer); + }; + const timer = window.setInterval(check, VIDEO_POLL_MS); + check(); + return () => { + window.clearInterval(timer); + cleanup?.(); + }; +} + +// Arriving from an Up next card keeps playing: the viewer already started the +// previous video in this tab, so the browser allows playback with sound. The +// ref is re-read on every tick because a soft navigation can keep the previous +// (ended) element mounted until the new player replaces it. +export function useContinueFromUpNext( + videoRef: RefObject, + videoId: string, +) { + useEffect(() => { + let pending = false; + try { + pending = window.sessionStorage.getItem(CONTINUE_STORAGE_KEY) === videoId; + } catch {} + if (!pending) return; + // Cleared only once handled, so a remount (or a development double + // effect) that cancels this poll leaves the request for the next one. + const clear = () => { + try { + window.sessionStorage.removeItem(CONTINUE_STORAGE_KEY); + } catch {} + }; + let tries = 0; + const timer = window.setInterval(() => { + const video = videoRef.current; + tries++; + if ( + video && + !video.ended && + video.paused && + video.currentTime < 1 && + video.readyState >= HTMLMediaElement.HAVE_FUTURE_DATA + ) { + window.clearInterval(timer); + clear(); + void video.play().catch(() => {}); + } else if (tries >= VIDEO_POLL_LIMIT) { + window.clearInterval(timer); + clear(); + } + }, VIDEO_POLL_MS); + return () => window.clearInterval(timer); + }, [videoRef, videoId]); +} diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsx index 30cb2bf1a57..115d08f3e6d 100644 --- a/apps/web/app/s/[videoId]/page.tsx +++ b/apps/web/app/s/[videoId]/page.tsx @@ -79,6 +79,7 @@ import { isSocialCrawlerUserAgent, SOCIAL_REFERRER_DOMAINS, } from "@/lib/social-crawlers"; +import { getSpaceUpNext } from "@/lib/space-up-next"; import { transcribeVideo } from "@/lib/transcribe"; import { areViewerDownloadsEnabled, @@ -499,7 +500,7 @@ async function AuthorizedContent({ }: { video: Omit< InferSelectModel, - "password" | "settings" | "ownerId" + "password" | "settings" | "ownerId" | "archivedAt" > & { owner: InferSelectModel; sharedOrganization: { organizationId: Organisation.OrganisationId } | null; @@ -876,6 +877,19 @@ async function AuthorizedContent({ return null; }); + const upNextPromise = + user && searchParams.space && !video.isScreenshot + ? getSpaceUpNext({ spaceParam: searchParams.space, videoId }).catch( + (error) => { + console.error( + `[ShareVideoPage] Up next lookup failed for ${videoId}:`, + error, + ); + return null; + }, + ) + : Promise.resolve(null); + const videoHasEditsPromise = memberCanDownloadPromise.then((canDownload) => { if (!canDownload || video.isScreenshot) return false; return db() @@ -908,6 +922,7 @@ async function AuthorizedContent({ resolvedImages, dashboardDestination, serverPlaybackSource, + upNext, ] = await Promise.all([ spacesDataPromise, sharedSpacesPromise, @@ -924,6 +939,7 @@ async function AuthorizedContent({ imagesPromise, dashboardDestinationPromise, serverPlaybackSourcePromise, + upNextPromise, viewNotificationPromise, ]); @@ -1087,6 +1103,7 @@ async function AuthorizedContent({ /> } dashboardDestination={dashboardDestination} + upNext={upNext} data={videoWithOrganizationInfo} initialPlaybackUrl={initialPlaybackUrlPromise} serverPlaybackUrl={ diff --git a/apps/web/app/s/[videoId]/types.ts b/apps/web/app/s/[videoId]/types.ts index 76ff1323a8d..21bda445a3c 100644 --- a/apps/web/app/s/[videoId]/types.ts +++ b/apps/web/app/s/[videoId]/types.ts @@ -4,7 +4,10 @@ import type { ImageUpload, Organisation, User } from "@cap/web-domain"; import type { OrganizationSettings } from "@/app/(org)/dashboard/dashboard-data"; import type { ShareCallToAction } from "@/lib/share-call-to-action"; -export type VideoData = Omit & { +export type VideoData = Omit< + typeof videos.$inferSelect, + "ownerId" | "archivedAt" +> & { owner: VideoOwner; organizationMembers?: User.UserId[]; organizationId?: Organisation.OrganisationId; diff --git a/apps/web/lib/space-up-next.ts b/apps/web/lib/space-up-next.ts new file mode 100644 index 00000000000..7814543f70d --- /dev/null +++ b/apps/web/lib/space-up-next.ts @@ -0,0 +1,69 @@ +import { db } from "@cap/database"; +import { getCurrentUser } from "@cap/database/auth/session"; +import { videos } from "@cap/database/schema"; +import { makeCurrentUserLayer, Spaces } from "@cap/web-backend"; +import { Space, Video } from "@cap/web-domain"; +import { eq } from "drizzle-orm"; +import { Effect } from "effect"; +import { runPromise } from "@/lib/server"; +import { nextInOrder, spaceVideoOrderFromSettings } from "./space-video-order"; +import { getSpaceRootVideoOrder } from "./space-video-order-query"; + +export type SpaceUpNext = { + spaceId: string; + spaceName: string; + video: { id: Video.VideoId; name: string; duration: number | null }; +}; + +const SPACE_ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/; + +// Only runs when a share page was opened from a Space (`?space=`), and only +// for a signed-in viewer the space policy lets in, so plain share links and +// anonymous viewers never pay for it. +export async function getSpaceUpNext({ + spaceParam, + videoId, +}: { + spaceParam: string | string[] | undefined; + videoId: Video.VideoId; +}): Promise { + const raw = Array.isArray(spaceParam) ? spaceParam[0] : spaceParam; + if (!raw || !SPACE_ID_PATTERN.test(raw)) return null; + + const user = await getCurrentUser(); + if (!user) return null; + + const spaceOrOrg = await Effect.flatMap(Spaces, (spaces) => + spaces.getSpaceOrOrg(Space.SpaceId.make(raw)), + ).pipe( + Effect.catchAll(() => Effect.succeed(null)), + Effect.provide(makeCurrentUserLayer(user)), + runPromise, + ); + if (!spaceOrOrg || spaceOrOrg.variant !== "space") return null; + const { space } = spaceOrOrg; + + const order = await getSpaceRootVideoOrder( + space.id, + spaceVideoOrderFromSettings(space.settings), + { includeScreenshots: false }, + ); + const nextId = nextInOrder( + order.map((row) => row.id), + videoId, + ); + if (!nextId) return null; + + const [next] = await db() + .select({ id: videos.id, name: videos.name, duration: videos.duration }) + .from(videos) + .where(eq(videos.id, Video.VideoId.make(nextId))) + .limit(1); + if (!next) return null; + + return { + spaceId: space.id, + spaceName: space.name, + video: { id: next.id, name: next.name, duration: next.duration }, + }; +} From c435e981ec0322a7f74b02a64a39f63011dc457e Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:35:03 +0000 Subject: [PATCH 05/16] feat(web): show Loom import status across the team to admins --- apps/web/actions/loom-import-overview.ts | 165 +++++++++++ .../dashboard/import/loom/ImportLoomPage.tsx | 7 + .../import/loom/LoomImportStatus.tsx | 260 ++++++++++++++++++ apps/web/lib/loom-import-status.ts | 48 ++++ 4 files changed, 480 insertions(+) create mode 100644 apps/web/actions/loom-import-overview.ts create mode 100644 apps/web/app/(org)/dashboard/import/loom/LoomImportStatus.tsx create mode 100644 apps/web/lib/loom-import-status.ts diff --git a/apps/web/actions/loom-import-overview.ts b/apps/web/actions/loom-import-overview.ts new file mode 100644 index 00000000000..0b2128aa770 --- /dev/null +++ b/apps/web/actions/loom-import-overview.ts @@ -0,0 +1,165 @@ +"use server"; + +import { db } from "@cap/database"; +import { getCurrentUser } from "@cap/database/auth/session"; +import { + importedVideos, + users, + videos, + videoUploads, +} from "@cap/database/schema"; +import type { Organisation } from "@cap/web-domain"; +import { and, desc, eq, inArray, sql } from "drizzle-orm"; +import { requireOrganizationSettingsAccess } from "@/actions/organization/authorization"; +import { + addLoomImportCounts, + emptyLoomImportCounts, + type LoomImportCounts, + type LoomImportState, + loomImportState, +} from "@/lib/loom-import-status"; + +const ATTENTION_LIMIT = 50; + +export type LoomImportMemberRow = LoomImportCounts & { + userId: string; + name: string | null; + email: string; + lastImportedAt: Date | null; +}; + +export type LoomImportAttentionRow = { + videoId: string; + name: string; + ownerName: string | null; + state: LoomImportState; + updatedAt: Date | null; +}; + +export type LoomImportOverview = { + totals: LoomImportCounts; + members: LoomImportMemberRow[]; + attention: LoomImportAttentionRow[]; +}; + +const phaseCount = (phases: string[]) => + sql`COALESCE(SUM(${videoUploads.phase} IN (${sql.join( + phases.map((phase) => sql`${phase}`), + sql`, `, + )})), 0)`.mapWith(Number); + +// Read-only, admins and owners only: every Loom import in the organization +// grouped by the member who owns it. imported_videos is keyed by org first, so +// this reads the org's own rows; deleted videos drop out through the join. +export async function getLoomImportOverview( + organizationId: string, +): Promise { + const user = await getCurrentUser(); + if (!user) throw new Error("Unauthorized"); + const access = await requireOrganizationSettingsAccess( + user.id, + organizationId as Organisation.OrganisationId, + ); + + const importScope = and( + eq(importedVideos.orgId, access.id), + eq(importedVideos.source, "loom"), + ); + + const [memberRows, attentionRows] = await Promise.all([ + db() + .select({ + userId: videos.ownerId, + name: users.name, + email: users.email, + total: sql`COUNT(*)`.mapWith(Number), + queued: phaseCount(["uploading"]), + importing: phaseCount(["processing", "generating_thumbnail"]), + failed: phaseCount(["error"]), + lastImportedAt: sql`MAX(${videos.createdAt})`.mapWith( + (value) => (value ? new Date(value) : null), + ), + }) + .from(importedVideos) + .innerJoin( + videos, + and(eq(videos.id, importedVideos.id), eq(videos.orgId, access.id)), + ) + .innerJoin(users, eq(users.id, videos.ownerId)) + .leftJoin(videoUploads, eq(videoUploads.videoId, videos.id)) + .where(importScope) + .groupBy(videos.ownerId, users.name, users.email), + db() + .select({ + videoId: videos.id, + name: videos.name, + ownerName: users.name, + phase: videoUploads.phase, + updatedAt: videoUploads.updatedAt, + }) + .from(importedVideos) + .innerJoin( + videos, + and(eq(videos.id, importedVideos.id), eq(videos.orgId, access.id)), + ) + .innerJoin(videoUploads, eq(videoUploads.videoId, videos.id)) + .leftJoin(users, eq(users.id, videos.ownerId)) + .where( + and( + importScope, + inArray(videoUploads.phase, [ + "error", + "uploading", + "processing", + "generating_thumbnail", + ]), + ), + ) + .orderBy( + sql`${videoUploads.phase} = 'error' DESC`, + desc(videoUploads.updatedAt), + ) + .limit(ATTENTION_LIMIT), + ]); + + const totals = emptyLoomImportCounts(); + const members = memberRows + .map((row) => { + const done = Math.max( + 0, + row.total - row.queued - row.importing - row.failed, + ); + const counts = addLoomImportCounts(emptyLoomImportCounts(), { + queued: row.queued, + importing: row.importing, + failed: row.failed, + done, + }); + addLoomImportCounts(totals, counts); + return { + ...counts, + userId: row.userId, + name: row.name, + email: row.email, + lastImportedAt: row.lastImportedAt, + }; + }) + .sort( + (a, b) => + b.failed - a.failed || + b.queued + b.importing - (a.queued + a.importing) || + b.total - a.total, + ); + + return { + totals, + members, + attention: attentionRows.map((row) => ({ + videoId: row.videoId, + name: row.name, + ownerName: row.ownerName, + state: loomImportState(row.phase), + updatedAt: row.updatedAt, + })), + }; +} diff --git a/apps/web/app/(org)/dashboard/import/loom/ImportLoomPage.tsx b/apps/web/app/(org)/dashboard/import/loom/ImportLoomPage.tsx index 895123c338b..394d6dcd90f 100644 --- a/apps/web/app/(org)/dashboard/import/loom/ImportLoomPage.tsx +++ b/apps/web/app/(org)/dashboard/import/loom/ImportLoomPage.tsx @@ -74,6 +74,7 @@ import { } from "@/lib/permissions/roles"; import { LoomAgentPromptRow } from "./LoomAgentPromptRow"; import { LoomConciergeRow } from "./LoomConciergeRow"; +import { LoomImportStatus } from "./LoomImportStatus"; type Mode = "single" | "csv"; @@ -1242,6 +1243,12 @@ export const ImportLoomPage = ({
)} + {canUseCsvImport && activeOrganization?.organization.id && ( + + )} + {canUseCsvImport && user.isPro && activeOrganization?.organization.id && ( diff --git a/apps/web/app/(org)/dashboard/import/loom/LoomImportStatus.tsx b/apps/web/app/(org)/dashboard/import/loom/LoomImportStatus.tsx new file mode 100644 index 00000000000..8098e127843 --- /dev/null +++ b/apps/web/app/(org)/dashboard/import/loom/LoomImportStatus.tsx @@ -0,0 +1,260 @@ +"use client"; + +import { faArrowsRotate } from "@fortawesome/free-solid-svg-icons/faArrowsRotate"; +import { faUsers } from "@fortawesome/free-solid-svg-icons/faUsers"; +import { useQuery } from "@tanstack/react-query"; +import clsx from "clsx"; +import { useId, useState } from "react"; +import { getLoomImportOverview } from "@/actions/loom-import-overview"; +import { FontAwesomeIcon } from "@/components/FontAwesomeIcon"; +import type { LoomImportState } from "@/lib/loom-import-status"; + +const STATE_LABELS: Record = { + queued: "Queued", + importing: "Importing", + done: "Done", + failed: "Failed", +}; + +const STATE_TONES: Record = { + queued: "bg-gray-3 text-gray-11", + importing: "bg-blue-3 text-blue-11", + done: "bg-gray-3 text-gray-11", + failed: "bg-red-transparent-20 text-red-400", +}; + +const ACTIVE_REFRESH_MS = 15_000; +const ATTENTION_PREVIEW = 6; + +const formatCount = (value: number) => value.toLocaleString("en-US"); + +const dateFormatter = new Intl.DateTimeFormat("en-US", { + month: "short", + day: "numeric", +}); + +function StatePill({ state }: { state: LoomImportState }) { + return ( + + {STATE_LABELS[state]} + + ); +} + +function CountCell({ + value, + state, +}: { + value: number; + state: LoomImportState; +}) { + return ( + + {formatCount(value)} + + ); +} + +export function LoomImportStatus({ + organizationId, +}: { + organizationId: string; +}) { + const titleId = useId(); + const [showAllAttention, setShowAllAttention] = useState(false); + const query = useQuery({ + queryKey: ["loom-import-overview", organizationId], + queryFn: () => getLoomImportOverview(organizationId), + refetchInterval: (current) => { + const totals = current.state.data?.totals; + return totals && totals.queued + totals.importing > 0 + ? ACTIVE_REFRESH_MS + : false; + }, + refetchOnWindowFocus: true, + }); + + const data = query.data; + if (query.isError) { + return ( +
+

+ Couldn't load your team's Loom imports. +

+ +
+ ); + } + if (!data || data.totals.total === 0) return null; + + return ( +
+
+
+
+ +
+
+

+ Imports across your team +

+

+ Every Loom video imported into this organization, by owner. +

+
+
+ +
+ +
+ {(["done", "importing", "queued", "failed"] as const).map((state) => ( +
+
{STATE_LABELS[state]}
+
0 + ? "text-red-400" + : "text-gray-12", + )} + > + {formatCount(data.totals[state])} +
+
+ ))} +
+ +
+ + + + + + + + + + + + + + {data.members.map((member) => ( + + + + + + + + + ))} + +
Loom imports by member
+ Member + + Done + + Importing + + Queued + + Failed + + Last import +
+

+ {member.name || member.email} +

+ {member.name && ( +

+ {member.email} +

+ )} +
+ {member.lastImportedAt + ? dateFormatter.format(new Date(member.lastImportedAt)) + : ""} +
+
+ + {data.attention.length > 0 && ( +
+

+ Still in progress or failed +

+
    + {(showAllAttention + ? data.attention + : data.attention.slice(0, ATTENTION_PREVIEW) + ).map((row) => ( +
  • + + + {row.name} + + {row.ownerName && ( + + {row.ownerName} + + )} + + +
  • + ))} +
+ {data.attention.length > ATTENTION_PREVIEW && ( + + )} +
+ )} +
+ ); +} diff --git a/apps/web/lib/loom-import-status.ts b/apps/web/lib/loom-import-status.ts new file mode 100644 index 00000000000..c107871b818 --- /dev/null +++ b/apps/web/lib/loom-import-status.ts @@ -0,0 +1,48 @@ +export type LoomImportState = "queued" | "importing" | "done" | "failed"; + +export const LOOM_IMPORT_STATES: readonly LoomImportState[] = [ + "queued", + "importing", + "done", + "failed", +]; + +// A Loom import keeps a video_uploads row until processing finishes; the +// workflow deletes it on success. "uploading" is the queued state written when +// the import is accepted, before the worker starts downloading. +export function loomImportState( + uploadPhase: string | null | undefined, +): LoomImportState { + switch (uploadPhase) { + case null: + case undefined: + case "complete": + return "done"; + case "uploading": + return "queued"; + case "error": + return "failed"; + default: + return "importing"; + } +} + +export type LoomImportCounts = Record & { + total: number; +}; + +export function emptyLoomImportCounts(): LoomImportCounts { + return { queued: 0, importing: 0, done: 0, failed: 0, total: 0 }; +} + +export function addLoomImportCounts( + into: LoomImportCounts, + from: Partial>, +): LoomImportCounts { + for (const state of LOOM_IMPORT_STATES) { + const value = from[state] ?? 0; + into[state] += value; + into.total += value; + } + return into; +} From 080dfd7d79c09e65d1ffa222aa10bc95bc9687bb Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:35:03 +0000 Subject: [PATCH 06/16] test(web): cover dashboard selection, ordering, archive and Loom status --- .github/workflows/infra-database.yml | 12 +- .../dashboard-library-database.test.ts | 369 ++++++++++++++++++ apps/web/__tests__/unit/cap-selection.test.ts | 79 ++++ apps/web/__tests__/unit/caps-keyboard.test.ts | 6 + .../unit/dashboard-library-helpers.test.ts | 88 +++++ .../unit/shared-caps-past-last-page.test.ts | 6 + .../__tests__/unit/space-video-order.test.ts | 128 ++++++ 7 files changed, 687 insertions(+), 1 deletion(-) create mode 100644 apps/web/__tests__/integration/dashboard-library-database.test.ts create mode 100644 apps/web/__tests__/unit/cap-selection.test.ts create mode 100644 apps/web/__tests__/unit/dashboard-library-helpers.test.ts create mode 100644 apps/web/__tests__/unit/space-video-order.test.ts diff --git a/.github/workflows/infra-database.yml b/.github/workflows/infra-database.yml index c94546baa8c..557f5751976 100644 --- a/.github/workflows/infra-database.yml +++ b/.github/workflows/infra-database.yml @@ -15,6 +15,11 @@ on: - "apps/web/lib/media-input-policy-strikes.ts" - "apps/web/actions/notifications/**" - "apps/web/actions/analytics/**" + - "apps/web/actions/caps/**" + - "apps/web/actions/spaces/video-order.ts" + - "apps/web/actions/videos/archive.ts" + - "apps/web/actions/loom-import-overview.ts" + - "apps/web/lib/space-video-order*" - "packages/database/schema.ts" - "packages/database/migrations/**" - ".github/workflows/infra-database.yml" @@ -32,6 +37,11 @@ on: - "apps/web/lib/media-input-policy-strikes.ts" - "apps/web/actions/notifications/**" - "apps/web/actions/analytics/**" + - "apps/web/actions/caps/**" + - "apps/web/actions/spaces/video-order.ts" + - "apps/web/actions/videos/archive.ts" + - "apps/web/actions/loom-import-overview.ts" + - "apps/web/lib/space-video-order*" - "packages/database/schema.ts" - "packages/database/migrations/**" - ".github/workflows/infra-database.yml" @@ -84,4 +94,4 @@ jobs: env: CAP_INFRA_TEST_DATABASE_URL: mysql://root@127.0.0.1:3306/cap_infra_tests CAP_INFRA_ROUND_TRIPS_DATABASE_URL: mysql://root@127.0.0.1:3306/cap_infra_tests - run: bun run vitest run __tests__/integration/infra-*-database.test.ts __tests__/integration/user-preferences-database.test.ts + run: bun run vitest run __tests__/integration/infra-*-database.test.ts __tests__/integration/user-preferences-database.test.ts __tests__/integration/dashboard-library-database.test.ts diff --git a/apps/web/__tests__/integration/dashboard-library-database.test.ts b/apps/web/__tests__/integration/dashboard-library-database.test.ts new file mode 100644 index 00000000000..c5876286ae2 --- /dev/null +++ b/apps/web/__tests__/integration/dashboard-library-database.test.ts @@ -0,0 +1,369 @@ +import { randomUUID } from "node:crypto"; +import * as Db from "@cap/database/schema"; +import type { Video } from "@cap/web-domain"; +import { eq, inArray, sql } from "drizzle-orm"; +import { drizzle, type MySql2Database } from "drizzle-orm/mysql2"; +import { createPool, type Pool } from "mysql2/promise"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; + +// Runs the dashboard library actions (page size, archive, select all, space +// custom order, Loom import status) against a real migrated MySQL database, +// including their permission checks. + +const fixture = vi.hoisted(() => ({ + database: undefined as unknown, + sessionUserId: "", +})); + +vi.mock("server-only", () => ({})); +vi.mock("@cap/database", async (importOriginal) => ({ + ...(await importOriginal()), + db: () => { + if (!fixture.database) throw new Error("Test database is not connected."); + return fixture.database; + }, +})); +vi.mock("@cap/database/auth/session", () => ({ + getCurrentUser: async () => { + const [user] = await (fixture.database as MySql2Database) + .select() + .from(Db.users) + .where(eq(Db.users.id, fixture.sessionUserId as never)); + return user ?? null; + }, +})); +vi.mock("next/cache", () => ({ revalidatePath: vi.fn() })); + +const databaseUrl = process.env.CAP_INFRA_TEST_DATABASE_URL; +const id = () => randomUUID().replaceAll("-", "").slice(0, 15); +const database = () => fixture.database as MySql2Database; + +const createUser = async (orgId: string, preferences?: "json-null") => { + const userId = id(); + await database() + .insert(Db.users) + .values({ + id: userId as never, + email: `${userId}@example.com`, + name: `Member ${userId.slice(0, 4)}`, + activeOrganizationId: orgId as never, + }); + if (preferences === "json-null") + await database() + .update(Db.users) + .set({ preferences: sql`CAST('null' AS JSON)` as never }) + .where(eq(Db.users.id, userId as never)); + return userId; +}; + +const createOrg = async () => { + const orgId = id(); + const ownerId = await createUser(orgId); + await database() + .insert(Db.organizations) + .values({ id: orgId as never, name: "Acme", ownerId: ownerId as never }); + return { orgId, ownerId }; +}; + +const addMember = async ( + orgId: string, + role: "member" | "admin" = "member", +) => { + const userId = await createUser(orgId); + await database() + .insert(Db.organizationMembers) + .values({ + id: id(), + userId: userId as never, + organizationId: orgId as never, + role: role as never, + }); + return userId; +}; + +const createVideo = async ( + ownerId: string, + orgId: string, + values: Partial = {}, +) => { + const videoId = id(); + await database() + .insert(Db.videos) + .values({ + id: videoId as never, + ownerId: ownerId as never, + orgId: orgId as never, + name: `Video ${videoId.slice(0, 4)}`, + ...values, + }); + return videoId as Video.VideoId; +}; + +describe.runIf(Boolean(databaseUrl))( + "dashboard library actions against a real database", + () => { + let pool: Pool; + + beforeAll(async () => { + if (!databaseUrl) throw new Error("Missing isolated test database URL."); + const url = new URL(databaseUrl); + if ( + url.protocol !== "mysql:" || + !["127.0.0.1", "localhost", "[::1]"].includes(url.hostname) || + !/^\/cap_infra_[a-z0-9_]+$/.test(url.pathname) + ) + throw new Error("These tests require a session-scoped local database."); + pool = createPool({ uri: databaseUrl, connectionLimit: 4 }); + fixture.database = drizzle(pool); + Object.assign(process.env, { + NEXT_PUBLIC_WEB_URL: "http://localhost", + WEB_URL: "http://localhost", + DATABASE_URL: databaseUrl, + NEXTAUTH_SECRET: "synthetic-test-secret-that-is-long-enough", + NEXTAUTH_URL: "http://localhost", + CAP_AWS_BUCKET: "synthetic", + CAP_AWS_REGION: "us-east-1", + CAP_AWS_ACCESS_KEY: "synthetic", + CAP_AWS_SECRET_KEY: "synthetic", + NODE_ENV: "test", + }); + }); + + afterAll(async () => { + await pool?.end(); + }); + + it("saves the page size on a JSON null account and keeps other keys", async () => { + const { setDashboardPageSize } = await import("@/actions/caps/page-size"); + const { orgId } = await createOrg(); + fixture.sessionUserId = await createUser(orgId, "json-null"); + await setDashboardPageSize(60); + await database() + .update(Db.users) + .set({ + preferences: sql`JSON_SET(preferences, '$.notifications', JSON_OBJECT('pauseViews', true))`, + }) + .where(eq(Db.users.id, fixture.sessionUserId as never)); + await setDashboardPageSize(100); + const [row] = await database() + .select({ preferences: Db.users.preferences }) + .from(Db.users) + .where(eq(Db.users.id, fixture.sessionUserId as never)); + expect(row?.preferences).toEqual({ + dashboard: { pageSize: 100 }, + notifications: { pauseViews: true }, + }); + await expect(setDashboardPageSize(999)).rejects.toThrow(); + }); + + it("archives only the owner's Caps, keeps updatedAt, and hides them from My Caps", async () => { + const { setVideosArchived } = await import("@/actions/videos/archive"); + const { listCapIdsInView } = await import("@/actions/caps/list-view-ids"); + const { orgId, ownerId } = await createOrg(); + const otherId = await addMember(orgId); + const updatedAt = new Date("2026-01-02T03:04:05Z"); + const mine = await createVideo(ownerId, orgId, { updatedAt }); + const kept = await createVideo(ownerId, orgId); + const theirs = await createVideo(otherId, orgId); + fixture.sessionUserId = ownerId; + + expect( + await setVideosArchived({ videoIds: [mine, theirs], archived: true }), + ).toEqual({ updated: 1 }); + + const rows = await database() + .select({ + id: Db.videos.id, + archivedAt: Db.videos.archivedAt, + updatedAt: Db.videos.updatedAt, + }) + .from(Db.videos) + .where(inArray(Db.videos.id, [mine, theirs])); + const byId = new Map(rows.map((row) => [row.id, row])); + expect(byId.get(mine)?.archivedAt).toBeInstanceOf(Date); + expect(byId.get(mine)?.updatedAt.toISOString()).toBe( + updatedAt.toISOString(), + ); + expect(byId.get(theirs)?.archivedAt).toBeNull(); + + expect((await listCapIdsInView({ type: "personal" })).sort()).toEqual( + [kept].sort(), + ); + expect(await listCapIdsInView({ type: "archived" })).toEqual([mine]); + + expect( + await setVideosArchived({ videoIds: [mine], archived: false }), + ).toEqual({ updated: 1 }); + expect((await listCapIdsInView({ type: "personal" })).sort()).toEqual( + [mine, kept].sort(), + ); + }); + + it("persists a custom space order for everyone and only lets managers change it", async () => { + const { reorderSpaceVideos, setSpaceVideoOrder } = await import( + "@/actions/spaces/video-order" + ); + const { getSpaceRootVideoOrder } = await import( + "@/lib/space-video-order-query" + ); + const { listCapIdsInView } = await import("@/actions/caps/list-view-ids"); + const { orgId, ownerId } = await createOrg(); + const memberId = await addMember(orgId); + const spaceId = id(); + await database() + .insert(Db.spaces) + .values({ + id: spaceId as never, + name: "Onboarding", + organizationId: orgId as never, + createdById: ownerId as never, + settings: { disableComments: true }, + }); + await database() + .insert(Db.spaceMembers) + .values({ + id: id(), + spaceId: spaceId as never, + userId: memberId as never, + role: "member", + }); + const videoIds: Video.VideoId[] = []; + for (let day = 1; day <= 4; day++) { + const videoId = await createVideo(ownerId, orgId, { + createdAt: new Date(`2026-03-0${day}T00:00:00Z`), + }); + videoIds.push(videoId); + await database() + .insert(Db.spaceVideos) + .values({ + id: id(), + spaceId: spaceId as never, + videoId, + addedById: ownerId as never, + }); + } + const [v1, v2, v3, v4] = videoIds as [ + Video.VideoId, + Video.VideoId, + Video.VideoId, + Video.VideoId, + ]; + const order = async (mode: "newest" | "custom") => + (await getSpaceRootVideoOrder(spaceId as never, mode)).map( + (row) => row.id, + ); + + expect(await order("newest")).toEqual([v4, v3, v2, v1]); + + fixture.sessionUserId = memberId; + await expect( + reorderSpaceVideos({ + spaceId, + videoIds: [v1], + placement: { type: "start" }, + }), + ).rejects.toThrow(); + await expect(setSpaceVideoOrder(spaceId, "custom")).rejects.toThrow(); + await expect( + listCapIdsInView({ type: "space", spaceId }), + ).rejects.toThrow(); + + fixture.sessionUserId = ownerId; + await reorderSpaceVideos({ + spaceId, + videoIds: [v1], + placement: { type: "start" }, + }); + expect(await order("custom")).toEqual([v1, v4, v3, v2]); + + await reorderSpaceVideos({ + spaceId, + videoIds: [v2], + placement: { type: "before", targetId: v4 }, + }); + expect(await order("custom")).toEqual([v1, v2, v4, v3]); + + const [space] = await database() + .select({ settings: Db.spaces.settings }) + .from(Db.spaces) + .where(eq(Db.spaces.id, spaceId as never)); + expect(space?.settings).toEqual({ + disableComments: true, + videoOrder: "custom", + }); + + const v5 = await createVideo(ownerId, orgId); + await database() + .insert(Db.spaceVideos) + .values({ + id: id(), + spaceId: spaceId as never, + videoId: v5, + addedById: ownerId as never, + }); + expect(await order("custom")).toEqual([v5, v1, v2, v4, v3]); + + await setSpaceVideoOrder(spaceId, "oldest"); + expect( + (await listCapIdsInView({ type: "space", spaceId })).sort(), + ).toEqual([v1, v2, v3, v4, v5].sort()); + }, 120_000); + + it("summarises Loom imports by member for admins only", async () => { + const { getLoomImportOverview } = await import( + "@/actions/loom-import-overview" + ); + const { orgId, ownerId } = await createOrg(); + const adminId = await addMember(orgId, "admin"); + const memberId = await addMember(orgId); + const phases: Array<[string, string | null]> = [ + [ownerId, null], + [ownerId, "error"], + [memberId, "uploading"], + [memberId, "processing"], + [memberId, "complete"], + ]; + for (const [owner, phase] of phases) { + const videoId = await createVideo(owner, orgId); + await database() + .insert(Db.importedVideos) + .values({ + id: videoId, + orgId: orgId as never, + source: "loom", + sourceId: id(), + }); + if (phase) + await database() + .insert(Db.videoUploads) + .values({ videoId, phase: phase as never }); + } + await createVideo(memberId, orgId); + + fixture.sessionUserId = memberId; + await expect(getLoomImportOverview(orgId)).rejects.toThrow(); + + fixture.sessionUserId = adminId; + const overview = await getLoomImportOverview(orgId); + expect(overview.totals).toEqual({ + queued: 1, + importing: 1, + done: 2, + failed: 1, + total: 5, + }); + const byUser = new Map(overview.members.map((m) => [m.userId, m])); + expect(byUser.get(ownerId)).toMatchObject({ done: 1, failed: 1 }); + expect(byUser.get(memberId)).toMatchObject({ + queued: 1, + importing: 1, + done: 1, + }); + expect(overview.attention.map((row) => row.state)).toEqual([ + "failed", + expect.any(String), + expect.any(String), + ]); + }); + }, +); diff --git a/apps/web/__tests__/unit/cap-selection.test.ts b/apps/web/__tests__/unit/cap-selection.test.ts new file mode 100644 index 00000000000..1ad283da723 --- /dev/null +++ b/apps/web/__tests__/unit/cap-selection.test.ts @@ -0,0 +1,79 @@ +import { describe, expect, it } from "vitest"; +import { + deselectPage, + pageSelectionState, + selectPage, + toggleSelection, +} from "@/lib/cap-selection"; + +const page = ["a", "b", "c", "d", "e", "f"]; + +const toggle = ( + selected: string[], + anchorId: string | null, + targetId: string, + shiftKey = false, +) => + toggleSelection({ orderedIds: page, selected, anchorId, targetId, shiftKey }); + +describe("toggleSelection", () => { + it("toggles a single Cap and makes it the anchor", () => { + expect(toggle([], null, "c")).toEqual({ selected: ["c"], anchorId: "c" }); + expect(toggle(["c"], "c", "c")).toEqual({ selected: [], anchorId: "c" }); + }); + + it("selects the whole range between the anchor and a shift-clicked Cap", () => { + const first = toggle([], null, "b"); + expect(toggle(first.selected, first.anchorId, "e", true)).toEqual({ + selected: ["b", "c", "d", "e"], + anchorId: "e", + }); + }); + + it("selects backwards ranges in page order", () => { + expect(toggle(["e"], "e", "b", true).selected).toEqual([ + "b", + "c", + "d", + "e", + ]); + }); + + it("deselects a range when the shift-clicked Cap was already selected", () => { + expect(toggle(["a", "b", "c", "d", "e"], "a", "d", true).selected).toEqual([ + "e", + ]); + }); + + it("keeps Caps already selected outside the range", () => { + expect(toggle(["a", "f"], "c", "d", true).selected).toEqual([ + "a", + "c", + "d", + "f", + ]); + }); + + it("falls back to a single toggle when there is no anchor on this page", () => { + expect(toggle([], null, "d", true).selected).toEqual(["d"]); + expect(toggle([], "z", "d", true).selected).toEqual(["d"]); + }); + + it("keeps selections from other pages", () => { + expect(toggle(["x1", "x2"], "b", "c").selected).toEqual(["x1", "x2", "c"]); + }); +}); + +describe("page selection", () => { + it("reports none, some and all", () => { + expect(pageSelectionState(page, [])).toBe("none"); + expect(pageSelectionState(page, ["a", "x"])).toBe("some"); + expect(pageSelectionState(page, [...page])).toBe("all"); + expect(pageSelectionState([], ["a"])).toBe("none"); + }); + + it("selects and clears the page without touching other pages", () => { + expect(selectPage(["a", "b"], ["x", "a"])).toEqual(["x", "a", "b"]); + expect(deselectPage(["a", "b"], ["x", "a", "b"])).toEqual(["x"]); + }); +}); diff --git a/apps/web/__tests__/unit/caps-keyboard.test.ts b/apps/web/__tests__/unit/caps-keyboard.test.ts index c97b14f8578..83f5bbec193 100644 --- a/apps/web/__tests__/unit/caps-keyboard.test.ts +++ b/apps/web/__tests__/unit/caps-keyboard.test.ts @@ -16,6 +16,12 @@ const mocks = vi.hoisted(() => ({ }, })); +vi.mock("@/app/(org)/dashboard/caps/components/CapListHeader", () => ({ + CapListHeader: () => null, + PageSizeSelect: () => null, + SelectAllCheckbox: () => null, + listControlClass: "", +})); vi.mock("@cap/ui", () => ({ Button: () => null })); vi.mock("@fortawesome/free-solid-svg-icons", () => ({ faFolderPlus: {}, diff --git a/apps/web/__tests__/unit/dashboard-library-helpers.test.ts b/apps/web/__tests__/unit/dashboard-library-helpers.test.ts new file mode 100644 index 00000000000..11dba3a2271 --- /dev/null +++ b/apps/web/__tests__/unit/dashboard-library-helpers.test.ts @@ -0,0 +1,88 @@ +import { describe, expect, it } from "vitest"; +import { + DEFAULT_DASHBOARD_PAGE_SIZE, + isDashboardPageSize, + resolveDashboardPageSize, +} from "@/lib/dashboard-page-size"; +import { + addLoomImportCounts, + emptyLoomImportCounts, + loomImportState, +} from "@/lib/loom-import-status"; +import { chunkIds } from "@/lib/video-archive"; + +describe("resolveDashboardPageSize", () => { + it("uses the saved preference, then falls back to 15", () => { + expect(resolveDashboardPageSize({})).toBe(DEFAULT_DASHBOARD_PAGE_SIZE); + expect(resolveDashboardPageSize({ preferences: null })).toBe(15); + expect( + resolveDashboardPageSize({ + preferences: { dashboard: { pageSize: 60 } }, + }), + ).toBe(60); + }); + + it("ignores saved values outside the menu", () => { + expect( + resolveDashboardPageSize({ + preferences: { dashboard: { pageSize: 5000 } }, + }), + ).toBe(15); + expect( + resolveDashboardPageSize({ + preferences: { dashboard: { pageSize: "60" } }, + }), + ).toBe(15); + }); + + it("keeps honouring ?limit= but never past 100", () => { + expect(resolveDashboardPageSize({ limitParam: "24" })).toBe(24); + expect(resolveDashboardPageSize({ limitParam: ["30", "60"] })).toBe(30); + expect(resolveDashboardPageSize({ limitParam: "100000" })).toBe(100); + expect( + resolveDashboardPageSize({ + limitParam: "0", + preferences: { dashboard: { pageSize: 30 } }, + }), + ).toBe(30); + expect(resolveDashboardPageSize({ limitParam: "abc" })).toBe(15); + }); + + it("only accepts the menu sizes", () => { + expect([15, 30, 60, 100].every(isDashboardPageSize)).toBe(true); + expect(isDashboardPageSize(20)).toBe(false); + expect(isDashboardPageSize("15")).toBe(false); + }); +}); + +describe("loomImportState", () => { + it("maps the upload phase a Loom import is in", () => { + expect(loomImportState(null)).toBe("done"); + expect(loomImportState(undefined)).toBe("done"); + expect(loomImportState("complete")).toBe("done"); + expect(loomImportState("uploading")).toBe("queued"); + expect(loomImportState("processing")).toBe("importing"); + expect(loomImportState("generating_thumbnail")).toBe("importing"); + expect(loomImportState("error")).toBe("failed"); + }); + + it("adds counts into totals", () => { + const totals = emptyLoomImportCounts(); + addLoomImportCounts(totals, { done: 3, failed: 1 }); + addLoomImportCounts(totals, { queued: 2 }); + expect(totals).toEqual({ + queued: 2, + importing: 0, + done: 3, + failed: 1, + total: 6, + }); + }); +}); + +describe("chunkIds", () => { + it("splits large selections into server-sized batches", () => { + expect(chunkIds([1, 2, 3, 4, 5], 2)).toEqual([[1, 2], [3, 4], [5]]); + expect(chunkIds([], 2)).toEqual([]); + }); +}); diff --git a/apps/web/__tests__/unit/shared-caps-past-last-page.test.ts b/apps/web/__tests__/unit/shared-caps-past-last-page.test.ts index b9e488f61ce..111d06bb0fd 100644 --- a/apps/web/__tests__/unit/shared-caps-past-last-page.test.ts +++ b/apps/web/__tests__/unit/shared-caps-past-last-page.test.ts @@ -9,6 +9,12 @@ const mocks = vi.hoisted(() => ({ marker: (name: string) => () => `[${name}]`, })); +vi.mock("@/app/(org)/dashboard/caps/components/CapListHeader", () => ({ + CapListHeader: () => null, + PageSizeSelect: () => null, + SelectAllCheckbox: () => null, + listControlClass: "", +})); vi.mock("next/navigation", () => ({ usePathname: () => "/dashboard/spaces/space-1", useRouter: () => ({ push: vi.fn(), refresh: vi.fn() }), diff --git a/apps/web/__tests__/unit/space-video-order.test.ts b/apps/web/__tests__/unit/space-video-order.test.ts new file mode 100644 index 00000000000..0f1486a24b2 --- /dev/null +++ b/apps/web/__tests__/unit/space-video-order.test.ts @@ -0,0 +1,128 @@ +import { describe, expect, it } from "vitest"; +import { + nextInOrder, + positionChanges, + reorderIds, + spaceVideoOrderFromSettings, +} from "@/lib/space-video-order"; + +const ids = ["a", "b", "c", "d", "e"]; + +describe("reorderIds", () => { + it("moves a Cap before or after another", () => { + expect(reorderIds(ids, ["e"], { type: "before", targetId: "b" })).toEqual([ + "a", + "e", + "b", + "c", + "d", + ]); + expect(reorderIds(ids, ["a"], { type: "after", targetId: "c" })).toEqual([ + "b", + "c", + "a", + "d", + "e", + ]); + }); + + it("moves a selection as one block in its current order", () => { + expect( + reorderIds(ids, ["d", "b"], { type: "before", targetId: "a" }), + ).toEqual(["b", "d", "a", "c", "e"]); + }); + + it("moves to the start, end, one earlier and one later", () => { + expect(reorderIds(ids, ["c"], { type: "start" })).toEqual([ + "c", + "a", + "b", + "d", + "e", + ]); + expect(reorderIds(ids, ["c"], { type: "end" })).toEqual([ + "a", + "b", + "d", + "e", + "c", + ]); + expect(reorderIds(ids, ["c"], { type: "earlier" })).toEqual([ + "a", + "c", + "b", + "d", + "e", + ]); + expect(reorderIds(ids, ["c"], { type: "later" })).toEqual([ + "a", + "b", + "d", + "c", + "e", + ]); + }); + + it("keeps the ends stable", () => { + expect(reorderIds(ids, ["a"], { type: "earlier" })).toEqual(ids); + expect(reorderIds(ids, ["e"], { type: "later" })).toEqual(ids); + }); + + it("ignores unknown ids and targets", () => { + expect(reorderIds(ids, ["zz"], { type: "start" })).toEqual(ids); + expect(reorderIds(ids, ["a"], { type: "before", targetId: "zz" })).toEqual( + ids, + ); + }); + + it("leaves the order alone when dropping a Cap onto itself", () => { + expect(reorderIds(ids, ["c"], { type: "before", targetId: "c" })).toEqual( + ids, + ); + }); +}); + +describe("positionChanges", () => { + it("assigns dense positions to every unplaced Cap", () => { + expect( + positionChanges( + [ + { id: "a", position: null }, + { id: "b", position: null }, + ], + ["b", "a"], + ), + ).toEqual([ + { id: "b", position: 0 }, + { id: "a", position: 1 }, + ]); + }); + + it("only rewrites the rows whose position changed", () => { + const current = ids.map((id, position) => ({ id, position })); + expect(positionChanges(current, ["b", "a", "c", "d", "e"])).toEqual([ + { id: "b", position: 0 }, + { id: "a", position: 1 }, + ]); + expect(positionChanges(current, ids)).toEqual([]); + }); +}); + +describe("space order helpers", () => { + it("defaults to newest first for old or unknown settings", () => { + expect(spaceVideoOrderFromSettings(null)).toBe("newest"); + expect(spaceVideoOrderFromSettings({})).toBe("newest"); + expect(spaceVideoOrderFromSettings({ videoOrder: "random" })).toBe( + "newest", + ); + expect(spaceVideoOrderFromSettings({ videoOrder: "custom" })).toBe( + "custom", + ); + }); + + it("finds the next Cap and stops at the end", () => { + expect(nextInOrder(ids, "b")).toBe("c"); + expect(nextInOrder(ids, "e")).toBeNull(); + expect(nextInOrder(ids, "zz")).toBeNull(); + }); +}); From 960e5205c6f998b9ebb329a5a0068d896642647b Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:00:55 +0000 Subject: [PATCH 07/16] fix(web): keep archive state out of the share playback type --- apps/web/lib/share-playback.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/web/lib/share-playback.ts b/apps/web/lib/share-playback.ts index 50f947f9d89..7199e6be61b 100644 --- a/apps/web/lib/share-playback.ts +++ b/apps/web/lib/share-playback.ts @@ -6,7 +6,7 @@ import { runPromise } from "@/lib/server"; type SharePlaybackVideo = Omit< typeof videos.$inferSelect, - "folderId" | "password" | "settings" | "ownerId" + "folderId" | "password" | "settings" | "ownerId" | "archivedAt" > & { owner: { id: User.UserId } }; export type SharePlaybackSource = { From 80b56ef52d036a3b77716f7ec0bff8c9ca02a5b2 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:16:00 +0000 Subject: [PATCH 08/16] fix(web): keep the delete shortcut to Caps on the current page --- apps/web/app/(org)/dashboard/caps/Caps.tsx | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/apps/web/app/(org)/dashboard/caps/Caps.tsx b/apps/web/app/(org)/dashboard/caps/Caps.tsx index 38202fd2e5c..9e45fd4ea90 100644 --- a/apps/web/app/(org)/dashboard/caps/Caps.tsx +++ b/apps/web/app/(org)/dashboard/caps/Caps.tsx @@ -245,9 +245,14 @@ export const Caps = ({ // Deleting is immediate and permanent, so the key only counts on the // page itself: not inside an open dialog (Move, Share), not while a // held key repeats, and not while the previous delete is running. + // The shortcut skips the confirmation dialog, so it only acts on + // Caps the viewer can see; "Select all" can reach thousands of + // Caps across pages, which must go through the confirmed button. + const pageIdSet = new Set(pageIds); if ( !e.repeat && !isDeletingCaps && + selectedCaps.every((id) => pageIdSet.has(id)) && !["INPUT", "TEXTAREA", "SELECT"].includes(active?.tagName || "") && !(active instanceof HTMLElement && active.isContentEditable) && !active?.closest('[role="dialog"], [role="alertdialog"]') @@ -266,7 +271,7 @@ export const Caps = ({ return () => { window.removeEventListener("keydown", handleKeyDown); }; - }, [selectedCaps, deleteCaps, isDeletingCaps]); + }, [selectedCaps, deleteCaps, isDeletingCaps, pageIds]); if ( !isArchivedView && From 8e62e3f40b340ab4e97997320b3c5e247411dab2 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:24:05 +0000 Subject: [PATCH 09/16] fix(web): apply concurrent space reorders one after the other --- apps/web/actions/spaces/video-order.ts | 33 +++++++++++++++++-------- apps/web/lib/space-video-order-query.ts | 6 +++-- 2 files changed, 27 insertions(+), 12 deletions(-) diff --git a/apps/web/actions/spaces/video-order.ts b/apps/web/actions/spaces/video-order.ts index 9715dc9ab36..20489b4b8bd 100644 --- a/apps/web/actions/spaces/video-order.ts +++ b/apps/web/actions/spaces/video-order.ts @@ -79,15 +79,27 @@ export async function reorderSpaceVideos(input: { const placement = input.placement; const id = await requireSpaceManager(input.spaceId); - const current = await getSpaceRootVideoOrder(id, "custom"); - const currentIds = current.map((row) => row.id as string); - const nextOrder = reorderIds(currentIds, videoIds, placement); - const changes = positionChanges( - current.map((row) => ({ id: row.id, position: row.position })), - nextOrder, - ); - - await db().transaction(async (tx) => { + // The space row is locked before the order is read, so two moves (two + // managers, or quick moves by one) apply one after the other instead of + // both computing positions from the same starting order. + const { nextOrder, changed } = await db().transaction(async (tx) => { + await tx + .select({ id: spaces.id }) + .from(spaces) + .where(eq(spaces.id, id)) + .for("update"); + const current = await getSpaceRootVideoOrder(id, "custom", { + executor: tx, + }); + const nextOrder = reorderIds( + current.map((row) => row.id as string), + videoIds, + placement, + ); + const changes = positionChanges( + current.map((row) => ({ id: row.id, position: row.position })), + nextOrder, + ); for (let i = 0; i < changes.length; i += POSITION_WRITE_CHUNK) { const chunk = changes.slice(i, i + POSITION_WRITE_CHUNK); await tx @@ -115,8 +127,9 @@ export async function reorderSpaceVideos(input: { .update(spaces) .set({ settings: videoOrderPatch("custom") }) .where(eq(spaces.id, id)); + return { nextOrder, changed: changes.length }; }); revalidatePath(`/dashboard/spaces/${id}`); - return { order: nextOrder, changed: changes.length }; + return { order: nextOrder, changed }; } diff --git a/apps/web/lib/space-video-order-query.ts b/apps/web/lib/space-video-order-query.ts index 64ee102b41b..421c0647a4c 100644 --- a/apps/web/lib/space-video-order-query.ts +++ b/apps/web/lib/space-video-order-query.ts @@ -30,12 +30,14 @@ export function spaceVideoOrderBy( return [desc(columns.effectiveCreatedAt), desc(columns.id)]; } +type QueryExecutor = Pick, "select">; + export async function getSpaceRootVideoOrder( spaceId: Space.SpaceIdOrOrganisationId, order: SpaceVideoOrder, - options: { includeScreenshots?: boolean } = {}, + options: { includeScreenshots?: boolean; executor?: QueryExecutor } = {}, ) { - const rows = await db() + const rows = await (options.executor ?? db()) .select({ id: videos.id, isScreenshot: videos.isScreenshot, From 6db2935b3cd6bcd3404080bf01d8e5260926c564 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:24:05 +0000 Subject: [PATCH 10/16] fix(web): say when select all stops at its limit --- apps/web/actions/caps/list-view-ids.ts | 21 ++++++++++++------- .../caps/components/SelectedCapsBar.tsx | 10 +++++++-- .../caps/components/useCapSelection.ts | 11 ++++++++-- 3 files changed, 30 insertions(+), 12 deletions(-) diff --git a/apps/web/actions/caps/list-view-ids.ts b/apps/web/actions/caps/list-view-ids.ts index cddba3cb5a7..57cae6ae6fd 100644 --- a/apps/web/actions/caps/list-view-ids.ts +++ b/apps/web/actions/caps/list-view-ids.ts @@ -18,18 +18,23 @@ import { type SelectAllView, } from "@/lib/select-all-view"; +const capped = (ids: Video.VideoId[]) => ({ + ids: ids.slice(0, MAX_SELECT_ALL_ITEMS), + truncated: ids.length > MAX_SELECT_ALL_ITEMS, +}); + // Returns the ids behind "Select all N" for the exact list the page shows, so a // bulk action can run past the current page. The same filters as the page // queries apply, and shared lists require the same rights that let the page // show selection at all. export async function listCapIdsInView( view: SelectAllView, -): Promise { +): Promise<{ ids: Video.VideoId[]; truncated: boolean }> { const user = await getCurrentUser(); if (!user) throw new Error("Unauthorized"); if (view.type === "personal" || view.type === "archived") { - if (!user.activeOrganizationId) return []; + if (!user.activeOrganizationId) return { ids: [], truncated: false }; const rows = await db() .select({ id: videos.id }) .from(videos) @@ -44,8 +49,8 @@ export async function listCapIdsInView( : isNotNull(videos.archivedAt), ), ) - .limit(MAX_SELECT_ALL_ITEMS); - return rows.map((row) => row.id); + .limit(MAX_SELECT_ALL_ITEMS + 1); + return capped(rows.map((row) => row.id)); } if (view.type === "space") { @@ -63,8 +68,8 @@ export async function listCapIdsInView( isNull(organizations.tombstoneAt), ), ) - .limit(MAX_SELECT_ALL_ITEMS); - return rows.map((row) => row.id); + .limit(MAX_SELECT_ALL_ITEMS + 1); + return capped(rows.map((row) => row.id)); } const access = await getOrganizationAccess( @@ -83,6 +88,6 @@ export async function listCapIdsInView( isNull(sharedVideos.folderId), ), ) - .limit(MAX_SELECT_ALL_ITEMS); - return rows.map((row) => row.id); + .limit(MAX_SELECT_ALL_ITEMS + 1); + return capped(rows.map((row) => row.id)); } diff --git a/apps/web/app/(org)/dashboard/caps/components/SelectedCapsBar.tsx b/apps/web/app/(org)/dashboard/caps/components/SelectedCapsBar.tsx index 3dd69b6887c..8798e05f4b9 100644 --- a/apps/web/app/(org)/dashboard/caps/components/SelectedCapsBar.tsx +++ b/apps/web/app/(org)/dashboard/caps/components/SelectedCapsBar.tsx @@ -28,6 +28,8 @@ interface SelectedCapsBarProps { CapSelection, | "canSelectAllMatching" | "isAllMatching" + | "matchingTruncated" + | "selectAllLimit" | "isSelectingAll" | "selectAllMatching" | "totalCount" @@ -101,11 +103,15 @@ export const SelectedCapsBar = ({ > {selection.isSelectingAll ? "Selecting..." - : `Select all ${selection.totalCount?.toLocaleString("en-US")}`} + : (selection.totalCount ?? 0) > selection.selectAllLimit + ? `Select the first ${selection.selectAllLimit.toLocaleString("en-US")}` + : `Select all ${selection.totalCount?.toLocaleString("en-US")}`} ) : selection?.isAllMatching ? (

- Every Cap here is selected + {selection.matchingTruncated + ? `The first ${selection.selectAllLimit.toLocaleString("en-US")} are selected` + : "Every Cap here is selected"}

) : ( moveLocation && diff --git a/apps/web/app/(org)/dashboard/caps/components/useCapSelection.ts b/apps/web/app/(org)/dashboard/caps/components/useCapSelection.ts index d519e1781a5..ecd29fa822e 100644 --- a/apps/web/app/(org)/dashboard/caps/components/useCapSelection.ts +++ b/apps/web/app/(org)/dashboard/caps/components/useCapSelection.ts @@ -12,7 +12,10 @@ import { selectPage, toggleSelection, } from "@/lib/cap-selection"; -import type { SelectAllView } from "@/lib/select-all-view"; +import { + MAX_SELECT_ALL_ITEMS, + type SelectAllView, +} from "@/lib/select-all-view"; export type CapSelection = ReturnType; @@ -29,6 +32,7 @@ export function useCapSelection({ }) { const [selected, setSelectedState] = useState([]); const [matchingCount, setMatchingCount] = useState(null); + const [matchingTruncated, setMatchingTruncated] = useState(false); const [isSelectingAll, setIsSelectingAll] = useState(false); const anchorRef = useRef(null); @@ -92,9 +96,10 @@ export function useCapSelection({ if (!view) return; setIsSelectingAll(true); try { - const ids = await listCapIdsInView(view); + const { ids, truncated } = await listCapIdsInView(view); setSelectedState(ids); setMatchingCount(ids.length); + setMatchingTruncated(truncated); } catch { toast.error("Couldn't select every Cap. Please try again."); } finally { @@ -151,6 +156,8 @@ export function useCapSelection({ pageState, canSelectAllMatching, isAllMatching, + matchingTruncated: isAllMatching && matchingTruncated, + selectAllLimit: MAX_SELECT_ALL_ITEMS, isSelectingAll, selectAllMatching, totalCount, From df75582faa211a2a80ccceb6d6a5af9b13d2be90 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:24:05 +0000 Subject: [PATCH 11/16] fix(web): only drag selections the move limit can carry --- .../(org)/dashboard/caps/components/CapCard/CapCard.tsx | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/apps/web/app/(org)/dashboard/caps/components/CapCard/CapCard.tsx b/apps/web/app/(org)/dashboard/caps/components/CapCard/CapCard.tsx index bf5b7407001..a16af0c2b68 100644 --- a/apps/web/app/(org)/dashboard/caps/components/CapCard/CapCard.tsx +++ b/apps/web/app/(org)/dashboard/caps/components/CapCard/CapCard.tsx @@ -51,6 +51,7 @@ import { useEffectMutation, useRpcClient } from "@/lib/EffectRuntime"; import { rejectOnFailure } from "@/lib/effect-react-query"; import { CAP_DRAG_TYPE, + MAX_MOVE_ITEMS, type MoveLocation, serializeCapDrag, } from "@/lib/move-items"; @@ -251,7 +252,12 @@ export const CapCard = ({ const isOwner = userId === cap.ownerId; const moveEnabled = Boolean(canMove && moveLocation && moveRootLabel); - const dragEnabled = moveEnabled && (!anyCapSelected || isSelected); + // A drag carries at most MAX_MOVE_ITEMS ids; larger selections ("Select + // all") go through the Move button, which sends them in batches. + const dragEnabled = + moveEnabled && + (!anyCapSelected || isSelected) && + (!isSelected || (selectedIds?.length ?? 0) <= MAX_MOVE_ITEMS); const queryClient = useQueryClient(); const uploadProgress = useUploadProgress( From 93e8581f67c8d04b3f57f1f4a645f64dbdfdfd0f Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:24:05 +0000 Subject: [PATCH 12/16] fix(web): refresh team Loom status after a CSV import --- apps/web/app/(org)/dashboard/import/loom/ImportLoomPage.tsx | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/apps/web/app/(org)/dashboard/import/loom/ImportLoomPage.tsx b/apps/web/app/(org)/dashboard/import/loom/ImportLoomPage.tsx index 394d6dcd90f..75267279af4 100644 --- a/apps/web/app/(org)/dashboard/import/loom/ImportLoomPage.tsx +++ b/apps/web/app/(org)/dashboard/import/loom/ImportLoomPage.tsx @@ -30,7 +30,7 @@ import { faFileCsv } from "@fortawesome/free-solid-svg-icons/faFileCsv"; import { faLink } from "@fortawesome/free-solid-svg-icons/faLink"; import { faTriangleExclamation } from "@fortawesome/free-solid-svg-icons/faTriangleExclamation"; import { faUpload } from "@fortawesome/free-solid-svg-icons/faUpload"; -import { useQuery } from "@tanstack/react-query"; +import { useQuery, useQueryClient } from "@tanstack/react-query"; import clsx from "clsx"; import { motion } from "framer-motion"; import Link from "next/link"; @@ -301,6 +301,7 @@ export const ImportLoomPage = ({ }) => { const { user, activeOrganization, spacesData } = useDashboardContext(); const router = useRouter(); + const queryClient = useQueryClient(); const searchParams = useSearchParams(); const prefilledLoomUrl = searchParams?.get("url")?.trim() ?? ""; const prefilledMode: Mode = @@ -671,6 +672,9 @@ export const ImportLoomPage = ({ )} started.`, ); router.refresh(); + void queryClient.invalidateQueries({ + queryKey: ["loom-import-overview"], + }); } else { toast.error(finalResult.error || "No Loom videos were imported."); } From 2c594b855ce613ff72727d7ddcc56dbd4dda8619 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:24:05 +0000 Subject: [PATCH 13/16] fix(web): report partial bulk move and archive results --- .../caps/components/MoveItemsDialog.tsx | 20 ++++++++++--- .../caps/components/useArchiveCaps.ts | 28 +++++++++++++++---- 2 files changed, 39 insertions(+), 9 deletions(-) diff --git a/apps/web/app/(org)/dashboard/caps/components/MoveItemsDialog.tsx b/apps/web/app/(org)/dashboard/caps/components/MoveItemsDialog.tsx index 99445b0eec4..1523b5c73be 100644 --- a/apps/web/app/(org)/dashboard/caps/components/MoveItemsDialog.tsx +++ b/apps/web/app/(org)/dashboard/caps/components/MoveItemsDialog.tsx @@ -183,16 +183,28 @@ export function MoveItemsDialog({ mutationFn: async () => { if (item.type === "videos") { if (!selectedGroup) throw new Error("Select a destination"); - // "Select all" can hold more Caps than one request accepts. + // "Select all" can hold more Caps than one request accepts. If a + // later batch fails, the earlier ones already moved, so say so and + // refresh instead of reporting a plain failure. + let moved = 0; for (const videoIds of chunkIds(item.videoIds, MAX_MOVE_ITEMS)) { const placement = { videoIds, folderId: selectedFolderId, location: selectedGroup.location, }; - await (ownedVideos - ? placeOwnedVideos({ ...placement, organizationId }) - : moveVideos(placement)); + try { + await (ownedVideos + ? placeOwnedVideos({ ...placement, organizationId }) + : moveVideos(placement)); + } catch (error) { + if (moved === 0) throw error; + router.refresh(); + throw new Error( + `Moved ${moved.toLocaleString("en-US")} of ${item.videoIds.length.toLocaleString("en-US")} Caps. Try again to move the rest.`, + ); + } + moved += videoIds.length; } return; } diff --git a/apps/web/app/(org)/dashboard/caps/components/useArchiveCaps.ts b/apps/web/app/(org)/dashboard/caps/components/useArchiveCaps.ts index d85dbcd7c8b..1faf8079d59 100644 --- a/apps/web/app/(org)/dashboard/caps/components/useArchiveCaps.ts +++ b/apps/web/app/(org)/dashboard/caps/components/useArchiveCaps.ts @@ -10,13 +10,23 @@ import { chunkIds, MAX_ARCHIVE_ITEMS } from "@/lib/video-archive"; const capsLabel = (count: number) => `${count.toLocaleString("en-US")} Cap${count === 1 ? "" : "s"}`; +class PartialArchiveError extends Error { + constructor(readonly doneIds: Video.VideoId[]) { + super("Some Caps were not updated"); + } +} + async function applyArchive(ids: Video.VideoId[], archived: boolean) { - let updated = 0; + const done: Video.VideoId[] = []; for (const chunk of chunkIds(ids, MAX_ARCHIVE_ITEMS)) { - const result = await setVideosArchived({ videoIds: chunk, archived }); - updated += result.updated; + try { + await setVideosArchived({ videoIds: chunk, archived }); + } catch (error) { + if (done.length > 0) throw new PartialArchiveError(done); + throw error; + } + done.push(...chunk); } - return updated; } export function useArchiveCaps({ @@ -35,7 +45,15 @@ export function useArchiveCaps({ setIsPending(true); try { await applyArchive(ids, archived); - } catch { + } catch (error) { + if (error instanceof PartialArchiveError) { + onDoneRef.current?.(error.doneIds); + router.refresh(); + toast.error( + `${archived ? "Archived" : "Unarchived"} ${error.doneIds.length.toLocaleString("en-US")} of ${capsLabel(ids.length)}. Try again for the rest.`, + ); + return; + } toast.error( archived ? "Couldn't archive. Please try again." From 5473f6f2041ae180a38a1cd9ebb3d8a387628b95 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:24:05 +0000 Subject: [PATCH 14/16] fix(web): follow late and fullscreen players for Up next --- .../s/[videoId]/_components/UpNextOverlay.tsx | 42 ++++++----- .../[videoId]/_components/up-next-playback.ts | 70 ++++++++----------- 2 files changed, 51 insertions(+), 61 deletions(-) diff --git a/apps/web/app/s/[videoId]/_components/UpNextOverlay.tsx b/apps/web/app/s/[videoId]/_components/UpNextOverlay.tsx index 6e204a2321e..09a042a4324 100644 --- a/apps/web/app/s/[videoId]/_components/UpNextOverlay.tsx +++ b/apps/web/app/s/[videoId]/_components/UpNextOverlay.tsx @@ -11,7 +11,7 @@ import { useState, } from "react"; import type { SpaceUpNext } from "@/lib/space-up-next"; -import { markUpNextContinue, whenVideoMounted } from "./up-next-playback"; +import { markUpNextContinue, onPlayerMediaEvent } from "./up-next-playback"; export const UP_NEXT_COUNTDOWN_SECONDS = 8; const AUTOPLAY_STORAGE_KEY = "cap:space-autoplay"; @@ -58,6 +58,7 @@ export function UpNextOverlay({ const [autoplay, setAutoplay] = useState(true); const [cancelled, setCancelled] = useState(false); const [remaining, setRemaining] = useState(UP_NEXT_COUNTDOWN_SECONDS); + const [fullscreen, setFullscreen] = useState(false); const navigatedRef = useRef(false); const href = upNextHref(upNext); @@ -65,24 +66,26 @@ export function UpNextOverlay({ setAutoplay(readAutoplay()); }, []); + useEffect( + () => + onPlayerMediaEvent(videoRef, ["ended", "play", "seeking"], (_, event) => { + if (event.type === "ended") { + setEnded(true); + setCancelled(false); + setRemaining(UP_NEXT_COUNTDOWN_SECONDS); + } else setEnded(false); + }), + [videoRef], + ); + + // The player goes fullscreen on its own root, which this card is not part + // of, so the countdown waits until the viewer can see it. useEffect(() => { - const onEnded = () => { - setEnded(true); - setCancelled(false); - setRemaining(UP_NEXT_COUNTDOWN_SECONDS); - }; - const onResume = () => setEnded(false); - return whenVideoMounted(videoRef, (video) => { - video.addEventListener("ended", onEnded); - video.addEventListener("play", onResume); - video.addEventListener("seeking", onResume); - return () => { - video.removeEventListener("ended", onEnded); - video.removeEventListener("play", onResume); - video.removeEventListener("seeking", onResume); - }; - }); - }, [videoRef]); + const update = () => setFullscreen(document.fullscreenElement !== null); + update(); + document.addEventListener("fullscreenchange", update); + return () => document.removeEventListener("fullscreenchange", update); + }, []); const playNext = useCallback(() => { if (navigatedRef.current) return; @@ -95,7 +98,8 @@ export function UpNextOverlay({ router.prefetch(href); }, [href, router]); - const counting = ended && autoplay && !cancelled && !holdAutoplay; + const counting = + ended && autoplay && !cancelled && !holdAutoplay && !fullscreen; useEffect(() => { if (!counting) return; diff --git a/apps/web/app/s/[videoId]/_components/up-next-playback.ts b/apps/web/app/s/[videoId]/_components/up-next-playback.ts index 07cdee8b961..ac44648de33 100644 --- a/apps/web/app/s/[videoId]/_components/up-next-playback.ts +++ b/apps/web/app/s/[videoId]/_components/up-next-playback.ts @@ -3,41 +3,42 @@ import { type RefObject, useEffect } from "react"; const CONTINUE_STORAGE_KEY = "cap:up-next-continue"; -const VIDEO_POLL_MS = 200; -const VIDEO_POLL_LIMIT = 150; + export function markUpNextContinue(videoId: string) { try { window.sessionStorage.setItem(CONTINUE_STORAGE_KEY, videoId); } catch {} } -// The player mounts after the page (and not at all while a video is still -// processing), so the element is looked up on a short, bounded poll. -export function whenVideoMounted( +// Media events don't bubble, but they do pass through capturing listeners on +// window. Listening there and matching the ref on each event works for a +// player that mounts late (a video still processing) or is swapped for a new +// element, without polling for it. +export function onPlayerMediaEvent( videoRef: RefObject, - onMounted: (video: HTMLVideoElement) => () => void, + types: readonly string[], + handler: (video: HTMLVideoElement, event: Event) => void, ) { - let cleanup: (() => void) | null = null; - let tries = 0; - const check = () => { + const listener = (event: Event) => { const video = videoRef.current; - if (video) { - window.clearInterval(timer); - cleanup = onMounted(video); - } else if (++tries >= VIDEO_POLL_LIMIT) window.clearInterval(timer); + if (video && event.target === video) handler(video, event); }; - const timer = window.setInterval(check, VIDEO_POLL_MS); - check(); + for (const type of types) window.addEventListener(type, listener, true); return () => { - window.clearInterval(timer); - cleanup?.(); + for (const type of types) window.removeEventListener(type, listener, true); }; } +const canStart = (video: HTMLVideoElement) => + !video.ended && + video.paused && + video.currentTime < 1 && + video.readyState >= HTMLMediaElement.HAVE_FUTURE_DATA; + // Arriving from an Up next card keeps playing: the viewer already started the // previous video in this tab, so the browser allows playback with sound. The -// ref is re-read on every tick because a soft navigation can keep the previous -// (ended) element mounted until the new player replaces it. +// request is cleared only once handled, so a remount (or a development double +// effect) leaves it for the next mount. export function useContinueFromUpNext( videoRef: RefObject, videoId: string, @@ -48,32 +49,17 @@ export function useContinueFromUpNext( pending = window.sessionStorage.getItem(CONTINUE_STORAGE_KEY) === videoId; } catch {} if (!pending) return; - // Cleared only once handled, so a remount (or a development double - // effect) that cancels this poll leaves the request for the next one. - const clear = () => { + let stop = () => {}; + const start = (video: HTMLVideoElement) => { + if (!canStart(video)) return; + stop(); try { window.sessionStorage.removeItem(CONTINUE_STORAGE_KEY); } catch {} + void video.play().catch(() => {}); }; - let tries = 0; - const timer = window.setInterval(() => { - const video = videoRef.current; - tries++; - if ( - video && - !video.ended && - video.paused && - video.currentTime < 1 && - video.readyState >= HTMLMediaElement.HAVE_FUTURE_DATA - ) { - window.clearInterval(timer); - clear(); - void video.play().catch(() => {}); - } else if (tries >= VIDEO_POLL_LIMIT) { - window.clearInterval(timer); - clear(); - } - }, VIDEO_POLL_MS); - return () => window.clearInterval(timer); + stop = onPlayerMediaEvent(videoRef, ["canplay", "loadeddata"], start); + if (videoRef.current) start(videoRef.current); + return () => stop(); }, [videoRef, videoId]); } From 40683c7f70ca1efc1198d52229d2506481c285f8 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:24:05 +0000 Subject: [PATCH 15/16] test(web): cover capped select all and concurrent reorders --- .../dashboard-library-database.test.ts | 36 ++++++++++++++++--- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/apps/web/__tests__/integration/dashboard-library-database.test.ts b/apps/web/__tests__/integration/dashboard-library-database.test.ts index c5876286ae2..42e983dad18 100644 --- a/apps/web/__tests__/integration/dashboard-library-database.test.ts +++ b/apps/web/__tests__/integration/dashboard-library-database.test.ts @@ -186,15 +186,18 @@ describe.runIf(Boolean(databaseUrl))( ); expect(byId.get(theirs)?.archivedAt).toBeNull(); - expect((await listCapIdsInView({ type: "personal" })).sort()).toEqual( + expect((await listCapIdsInView({ type: "personal" })).ids.sort()).toEqual( [kept].sort(), ); - expect(await listCapIdsInView({ type: "archived" })).toEqual([mine]); + expect(await listCapIdsInView({ type: "archived" })).toEqual({ + ids: [mine], + truncated: false, + }); expect( await setVideosArchived({ videoIds: [mine], archived: false }), ).toEqual({ updated: 1 }); - expect((await listCapIdsInView({ type: "personal" })).sort()).toEqual( + expect((await listCapIdsInView({ type: "personal" })).ids.sort()).toEqual( [mine, kept].sort(), ); }); @@ -303,9 +306,34 @@ describe.runIf(Boolean(databaseUrl))( }); expect(await order("custom")).toEqual([v5, v1, v2, v4, v3]); + await Promise.all([ + reorderSpaceVideos({ + spaceId, + videoIds: [v3], + placement: { type: "start" }, + }), + reorderSpaceVideos({ + spaceId, + videoIds: [v4], + placement: { type: "start" }, + }), + ]); + const positions = await database() + .select({ position: Db.spaceVideos.position }) + .from(Db.spaceVideos) + .where(eq(Db.spaceVideos.spaceId, spaceId as never)); + expect( + positions + .map((row) => row.position) + .sort((a, b) => Number(a) - Number(b)), + ).toEqual([0, 1, 2, 3, 4]); + expect((await order("custom")).slice(0, 2).sort()).toEqual( + [v3, v4].sort(), + ); + await setSpaceVideoOrder(spaceId, "oldest"); expect( - (await listCapIdsInView({ type: "space", spaceId })).sort(), + (await listCapIdsInView({ type: "space", spaceId })).ids.sort(), ).toEqual([v1, v2, v3, v4, v5].sort()); }, 120_000); From 0b28f1d041d1ef3a679fd8909e9b364089eb9525 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:27:35 +0000 Subject: [PATCH 16/16] test(web): drop the narrating header from the dashboard database suite --- .../__tests__/integration/dashboard-library-database.test.ts | 4 ---- 1 file changed, 4 deletions(-) diff --git a/apps/web/__tests__/integration/dashboard-library-database.test.ts b/apps/web/__tests__/integration/dashboard-library-database.test.ts index 42e983dad18..14d9ad3a7da 100644 --- a/apps/web/__tests__/integration/dashboard-library-database.test.ts +++ b/apps/web/__tests__/integration/dashboard-library-database.test.ts @@ -6,10 +6,6 @@ import { drizzle, type MySql2Database } from "drizzle-orm/mysql2"; import { createPool, type Pool } from "mysql2/promise"; import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; -// Runs the dashboard library actions (page size, archive, select all, space -// custom order, Loom import status) against a real migrated MySQL database, -// including their permission checks. - const fixture = vi.hoisted(() => ({ database: undefined as unknown, sessionUserId: "",